【问题标题】:How to bin the summarised frequency table with dplyr如何使用 dplyr 对汇总频率表进行分箱
【发布时间】:2019-01-11 09:16:57
【问题描述】:

我有以下数据框:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
df <- nycflights13::flights %>% 
  select(distance) %>% 
  group_by(distance) %>% 
  summarise(n = n()) %>% 
  arrange(distance) %>% ungroup() 

df
#> # A tibble: 214 x 2
#>    distance     n
#>       <dbl> <int>
#>  1       17     1
#>  2       80    49
#>  3       94   976
#>  4       96   607
#>  5      116   443
#>  6      143   439
#>  7      160   376
#>  8      169   545
#>  9      173   221
#> 10      184  5504
#> # … with 204 more rows

我想要做的是将distance 列按大小为 100 的 bin, 并相应地对n 列求和。 怎么能这样?

所以你会得到类似的东西:

bin_distance sum_n
1-100       1633  #(1 + 49 + 976 + 607)
101-200     21344 # (443 + ... + 5327)
#etc

【问题讨论】:

    标签: r dplyr tidyverse


    【解决方案1】:

    最简单的方法是使用cut,方法是使用seq 为每100 个值创建groupssum 为每个组创建值。

    library(dplyr)
    
    df %>%
      group_by(group = cut(distance, breaks = seq(0, max(distance), 100))) %>%
      summarise(n = sum(n))
    
    
    #   group         n
    #   <fct>       <int>
    # 1 (0,100]      1633
    # 2 (100,200]   21344
    # 3 (200,300]   28310
    # 4 (300,400]    7748
    # 5 (400,500]   21292
    # 6 (500,600]   26815
    # 7 (600,700]    7846
    # 8 (700,800]   48904
    # 9 (800,900]    7574
    #10 (900,1e+03] 18205
    # ... with 17 more rows
    

    可以使用aggregate like 翻译成基础 R

    aggregate(n ~ distance, 
     transform(df, distance = cut(distance, breaks = seq(0, max(distance), 100))), sum)
    

    【讨论】:

      【解决方案2】:

      不同的tidyverse 解决方案。它紧跟@Ronak Shah 代码的逻辑,但不是使用cut(),而是使用来自ggplot2cut_width()

      nycflights13::flights %>%
       select(distance) %>%
       group_by(ints = cut_width(distance, width = 100, boundary = 0)) %>%
       summarise(n = n())
      
         ints            n
         <fct>       <int>
       1 [0,100]      1633
       2 (100,200]   21344
       3 (200,300]   28310
       4 (300,400]    7748
       5 (400,500]   21292
       6 (500,600]   26815
       7 (600,700]    7846
       8 (700,800]   48904
       9 (800,900]    7574
      10 (900,1e+03] 18205
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-03
        相关资源
        最近更新 更多