Reputation: 73
I would like to apply a function to all column in data.table. Hence, I use .SD with lapply. But, inside lapply I cannot retrieve the column of my table.
For instance
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
I do the following:
x[,lapply(.SD,function(t){t*x$id}),.SDcols=c(1,2)]
Can we do better?
Upvotes: 7
Views: 1061
Reputation: 8753
just remove .SDcols=c(1,2)
. that removes the third column (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
to not have the id
, all the following will work:
x[,lapply(.SD[,list(a,b)], `*`, id)]
x[,lapply(.SD[,-3], `*`, id)]
x[,lapply(.SD, `*`,id)][, list(a,b)]
Upvotes: 5