在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
Run Code Online (Sandbox Code Playgroud)
我想做的是DT[,val]当id为"CTRL"时取平均值.
我通常会aggregate使用数据框,然后使用match将值映射回新列'ctrl'.
使用data.table包我可以得到:
DT[id=="CTRL",ctrl:=mean(val),by=plate]
> DT
plate id val ctrl
1: plate1 …Run Code Online (Sandbox Code Playgroud)