Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R data.table syntax to create and select on the fly

Tags:

r

data.table

I have a data.table in R that I would like to modify one of the columns on the fly (but not change the original object) and select a limited number of its columns afterwards by reference. Best I managed is as follows but then my column names are changed, any suggestions?

tmp <- data.table(a = 'X', b = 'Y', d = 1)
tmp[,.(d = d * - 1, .SD), .SDcols = colNames]

like image 911
Burak Oker Avatar asked Dec 05 '25 18:12

Burak Oker


1 Answers

try c(list(d=d*-1), .SD) in j argument

j expects a list
.SD is a list

So when adding new column like this you just need to put it into list and combine with c function.

like image 73
jangorecki Avatar answered Dec 08 '25 10:12

jangorecki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!