繁体   English   中英

Demean R data.table:列列表

[英]Demean R data.table: list of columns

我想按组data.table整个data.table对象(或只是它的许多列的列表)。

到目前为止,这是我的方法:

setkey(myDt, groupid)
for (col in colnames(wagesOfFired)){
   myDt[, paste(col, 'demeaned', sep='.') := col - mean(col), with=FALSE]
}

这使

Error in col - mean(col) : non-numeric argument to binary operator

这是一些示例数据。 在这种简单的情况下,只有两列,但是我通常有很多列,因此我想遍历列表

            y  groupid    x
 1:   3.46000 51557094   97
 2: 111.60000 51557133   25
 3:  29.36000 51557133   23
 4:  96.38000 51557133    9
 5:  65.22000 51557193   32
 6:  66.05891 51557328   10
 7:   9.74000 51557328  180
 8:  61.59000 51557328   18
 9:   9.99000 51557328   18
10:  89.68000 51557420  447
11: 129.24436 51557429   15
12:   3.46000 51557638 3943
13: 117.36000 51557642   11
14:   9.51000 51557653   83
15:  68.16000 51557653  518
16:  96.38000 51557653   14
17:   9.53000 51557678   18
18:   7.96000 51557801  266
19:  51.88000 51557801   49
20:  10.70000 51558040 1034

问题在于col是一个字符串,因此无法计算col-mean(col)

myNames <- names(myDt)
myDt[,paste(myNames,"demeaned",sep="."):=
  lapply(.SD,function(x)x-mean(x)),
by=groupid,.SDcols=myNames]

评论:

  • 您不需要设置密钥。
  • 这是一项操作,因为重复使用[可能会很慢。
  • 您可以将myNames更改为列名称的某些子集。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM