簡體   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