首页 > 解决方案 > 如何在 R 的区间中计算“小标题的特定变量的值的数量”?

问题描述

需要的包

'dplyr'

'nycflights13'

我正在使用的小标题是

 q4<-flights%>%group_by(year,month,day)%>%summarise(cancelled=sum(is.na(dep_time)),avg_delay=mean(arr_delay,na.rm = T),totalflights=n())

 q4<-q4%>%mutate(prop=cancelled/totalflights)

使用

q4%>%ungroup()%>%count(prop)

给我

     # A tibble: 342 x 2
       prop     n
       <dbl> <int>
    1 0           7
    2 0.00101     1
    3 0.00102     2
    4 0.00102     1
    5 0.00102     1
    6 0.00102     1
    7 0.00103     1
    8 0.00103     1
    9 0.00104     1
    10 0.00104     1
    # ... with 332 more rows

有没有一种方法可以(不使用 for 循环等蛮力逻辑)以所需的形式获得输出,我正在寻找单行或两行解决方案。dplyr 中是否有一个功能可以做到这一点?

期望的输出:

     # A tibble: X x Y
       prop     n
       <dbl> <int>
    1 0-0.1       45          #random numbers
    2 0.1-0.2     54
    3 0.2-0.3     23

标签: rdplyr

解决方案


下面,我使用cutbin 数据,然后table计算每个 bin 的实例。

data.frame(cut(q4$prop, breaks = c(0, 0.1, 0.2, 0.3)) %>% table)

生产

#           . Freq
# 1   (0,0.1]  341
# 2 (0.1,0.2]   13
# 3 (0.2,0.3]    2

推荐阅读