Demean R data.table:列列表

Foo*_*Bar 1 r data.table

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

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

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

这使

Error in col - mean(col) : non-numeric argument to binary operator
Run Code Online (Sandbox Code Playgroud)

这是一些示例数据.在这个简单的例子中,只有两列,但我通常有很多列,所以我想迭代列表

            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
Run Code Online (Sandbox Code Playgroud)

Fra*_*ank 7

问题是这col是一个字符串,所以col-mean(col)无法计算.

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

评论:

  • 您无需设置密钥.
  • 这是一次操作,因为[重复使用可能会很慢.
  • 您可以更改myNames为列名的某个子集.