本文介绍了data.table drop key rows和summarize的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种优雅的方式来遍历data.table的键,删除具有该键的行,然后对剩余行进行摘要。例如:

I'm looking for an elegant way to iterate over the key of data.table, drop the rows that have that key, then take a summary over the remaining rows. For example:

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))

有没有办法循环键,优雅地做?感谢。

Is there a way to loop over the key and do this elegantly? Thanks.

推荐答案

我认为这样做,使用更传统的 data.table code:

I think this does it, using more traditional data.table code:

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

这篇关于data.table drop key rows和summarize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:53