Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R, data.table: How to assign values of some columns based on the names of other columns, which are stored in a character vector?

Tags:

r

data.table

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

like image 697
Aldo Pareja Avatar asked Feb 08 '23 08:02

Aldo Pareja


1 Answers

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

  • As @DavidArenburg explained, the parentheses in (names1) := ensure that we look at the content of the names1 vector instead of making a column named "names1".
  • I'd suggest going through the first vignette for the package for details on .SDcols.
  • mget finds objects based on their names and puts them into a list.
like image 186
Frank Avatar answered Feb 16 '23 03:02

Frank