大家好,我有一个这样的数据框:
value count
<dbl> <dbl>
1 1 10
2 2 20
3 3 30
4 4 40
5 5 50
6 6 60
Run Code Online (Sandbox Code Playgroud)
我希望能够将我的观察划分为间隔。第一个和最后一个间隔必须包括超出范围的所有观察值(例如 2)
interval count
<???> <dbl>
1 [<1, 2] 30
2 [3, 4] 50
3 [5, >6] 110
Run Code Online (Sandbox Code Playgroud)
可以用 dplyr 做到这一点吗?
您可以使用cut()创建一个分组变量来汇总计数。
library(dplyr)
df %>%
group_by(grp = cut(value, c(-Inf, 2, 4, Inf))) %>%
summarise(count = sum(count))
# A tibble: 3 x 2
grp count
<fct> <int>
1 (-Inf,2] 30
2 (2,4] 70
3 (4, Inf] 110
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
302 次 |
| 最近记录: |