I have the following data table:
dt=data.table(a=seq(1,3),b=letters[seq(1,3)],
c=seq(4,6),d=letters[seq(4,6)])
dt
a b c d
1: 1 a 4 d
2: 2 b 5 e
3: 3 c 6 f
I store the names of some columns in one vector and the names of other columns in another vector:
names1=names(dt)[1:2]
names2=names(dt)[3:4]
I need to assign the values of the columns stored in names2 to the columns of names1 when some conditions apply. Something like
dt[c(2,3),names1:=names2]
dt
a b c d
1: 1 a 4 d
2: 5 e 5 e
3: 6 f 6 f
I have tried the following syntax without success:
dt[c(2,3),names1:=dt[c(2,3),names2,with=F]]
But it still tries to assign the values of the string vectors contained in names2
I would do
dt[2:3, (names1) := .SD, .SDcols = names2]
Or an alternative approach, thanks to @DavidArenburg:
dt[c(2,3), (names1) := mget(names2)]
How it works
(names1) :=
ensure that we look at the content of the names1
vector instead of making a column named "names1"
. .SDcols
.mget
finds objects based on their names and puts them into a list.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With