根据关联数值变量的大小对数据框中的数据求和

Sum count data in a dataframe based on the size of an associated numeric variable

我有一个数据框,数据如下(虽然我的数据集大很多)

ID  Count  Size
1   1      35
1   2      42
1   2      56
2   3      25
2   5      52
2   2      62

等....

我想提取每个 ID 的总计数,但当大小变量为 <50 或 <=50 时拆分

到目前为止,我这样做是为了根据唯一 ID 获取累积计数

cbind(aggregate(Count~ID, sum, data=df)

制作这个

ID Count
1  5
2  10

但我想制作这样的东西

ID  <50  >=50
1   3    2
2   3    7

我已经尝试搜索如何最好地做到这一点,并确信它真的很简单,但我正在努力寻找如何最好地实现这一点...任何帮助都将非常感谢!

我们可以使用 data.table。将'data.frame'转换为'data.table'(setDT(df1)),按'ID'分组,根据逻辑索引得到'Count'的sum('尺寸 < 50,尺寸 >=50`)

library(data.table)
setDT(df1)[,list(`<50` = sum(Count[Size <50]), 
            `>=50` = sum(Count[Size>=50])) , by = ID]
#   ID <50 >=50
#1:  1   3    2
#2:  2   3    7

dplyr 类似的选项是

library(dplyr)
df1 %>%
    group_by(ID) %>% 
    summarise(`<50` = sum(Count[Size <50]),
             `>=50` = sum(Count[Size>=50]))

注意:最好将列命名为 less50greaterthanEq50 而不是预期输出中建议的名称。

继续你的想法,你实际上可以在 df[df$Size<50,]aggregate 而不是 df,然后再次执行此操作 >=50 然后合并。

d1 = aggregate(Count~ID,sum,data=df[df$Size<50,])
d2 = aggregate(Count~ID,sum,data=df[df$Size>=50,])
merge(d1,d2,by="ID",all=TRUE)

这只是基于你已经做过的,但不是我猜的最好的..