我正在寻找一种优雅的方法来迭代data.table的键,删除具有该键的行,然后对剩余的行进行汇总。例如:
mydt <- data.table(cat=c("a","a","b","b","c","c","c"), vals = 1:7)
setkey(mydt,cat)
tmp1 <- mydt[!"a"][,mean(vals)]
tmp2 <- mydt[!"b"][,mean(vals)]
tmp3 <- mydt[!"c"][,mean(vals)]
outdt <- data.table(cat=c("a","b","c"),means=c(tmp1,tmp2,tmp3))
有没有办法循环键并优雅地执行此操作?感谢。
答案 0 :(得分:10)
我认为这样做,使用更传统的data.table
代码:
setkey(mydt,cat)
mydt[, list(means=mean(mydt[!.BY,vals])), by=cat]
# or without needing to key first
mydt[, list(means=mean(mydt[cat != .BY,vals])), by=cat]
# cat means
#1: a 5.0
#2: b 4.2
#3: c 2.5