我想将一个函数应用于data.table中的所有列.因此,我使用.SD与lapply.但是,在lapply内部,我无法检索我的表的列. 例如 x = data.table(a=1:10, b=10:1, id=1:5)x[,lapply(.SD,function(t){t*id}),.SDcols=c(1,2)]Error i
例如
x = data.table(a=1:10, b=10:1, id=1:5)
x[,lapply(.SD,function(t){t*id}),.SDcols=c(1,2)]
Error in ..FUN(a) : object 'id' not found
我做以下事情:
x[,lapply(.SD,function(t){t*x$id}),.SDcols=c(1,2)]
我们可以做得更好吗?
只需删除.SDcols = c(1,2).删除第三列(id)> x[,lapply(.SD,function(t){t*id})]
a b id
1: 1 10 1
2: 4 18 4
3: 9 24 9
4: 16 28 16
5: 25 30 25
6: 6 5 1
7: 14 8 4
8: 24 9 9
9: 36 8 16
10: 50 5 25
如果没有id,以下所有内容都将起作用:
x[,lapply(.SD[,list(a,b)], `*`, id)] x[,lapply(.SD[,-3, with=F], `*`, id)] x[,lapply(.SD, `*`,id)][, list(a,b)]
