微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用data.table进行聚合

在SO用户的多个建议之后,我终于尝试将我的代码转换为使用data.table.

library(data.table)
DT <- data.table(plate = paste0("plate",rep(1:2,each=5)),id = rep(c("CTRL","CTRL","ID1","ID2","ID3"),2),val = 1:10)

> DT
    plate   id val
1: plate1 CTRL   1
2: plate1 CTRL   2
3: plate1  ID1   3
4: plate1  ID2   4
5: plate1  ID3   5
6: plate2 CTRL   6
7: plate2 CTRL   7
8: plate2  ID1   8
9: plate2  ID2   9
10: plate2  ID3  10

我想做的是当id为“CTRL”时,按平均值DT [,val]取平均值.

我通常会聚合数据框,然后使用匹配将值映射回新列’ctrl’.

使用data.table包我可以得到:

DT[id=="CTRL",ctrl:=mean(val),by=plate]

> DT
    plate   id val ctrl
1: plate1 CTRL   1  1.5
2: plate1 CTRL   2  1.5
3: plate1  ID1   3   NA
4: plate1  ID2   4   NA
5: plate1  ID3   5   NA
6: plate2 CTRL   6  6.5
7: plate2 CTRL   7  6.5
8: plate2  ID1   8   NA
9: plate2  ID2   9   NA
10: plate2  ID3  10   NA

我真正需要的是:

DT <- data.table(plate = paste0("plate",val = 1:10,ctrl = rep(c(1.5,6.5),each=5))

> DT
    plate   id val ctrl
1: plate1 CTRL   1  1.5
2: plate1 CTRL   2  1.5
3: plate1  ID1   3  1.5
4: plate1  ID2   4  1.5
5: plate1  ID3   5  1.5
6: plate2 CTRL   6  6.5
7: plate2 CTRL   7  6.5
8: plate2  ID1   8  6.5
9: plate2  ID2   9  6.5
10: plate2  ID3  10  6.5

最后我想使用更复杂的值选择,但我不知道如何选择特定值,运行一些函数,然后使用数据框将这些值映射回适当的行.

解决方法

这是你想要做的:

DT[,ctrl:=mean(val[id=="CTRL"]),by=plate]

这使

plate   id val ctrl
 1: plate1 CTRL   1  1.5
 2: plate1 CTRL   2  1.5
 3: plate1  ID1   3  1.5
 4: plate1  ID2   4  1.5
 5: plate1  ID3   5  1.5
 6: plate2 CTRL   6  6.5
 7: plate2 CTRL   7  6.5
 8: plate2  ID1   8  6.5
 9: plate2  ID2   9  6.5
10: plate2  ID3  10  6.5

您的原始代码DT [id ==“CTRL”,ctrl:= mean(val),by = plate]没有为id ==“CTRL”的行进行赋值,因为当您使用第一个参数时[,你是子集;第二个参数中的操作仅针对子集化data.table进行.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐