Shawn Brar
Shawn Brar

Reputation: 1420

Join in place multiple columns data.table

I need to join in place more than 20 columns using data.table and I cannot use the syntax in the following link, since, that would mean writing the names of the columns multiple times. I can provide an example in which I have to join 5 columns (in my actual data there are more than 20):-

data <- data.table(ref = 1:6, names = letters[1:6])
b <- data.table(ref = 1:6, radius = runif(6), height = rnorm(6), weight = rnorm(6), volume = rnorm(6), money = rnorm(6))

And I don't want to write the names of the columns while joining them like following:-

data[b, colnames(b)[-1] := .(i.radius, i.height, i.weight, i.volume, i.money), on = "ref"]

Is there any way to write the RHS in like a vector form.

Upvotes: 2

Views: 458

Answers (1)

Waldi
Waldi

Reputation: 41220

A possible solution with mget :

cols <- colnames(b)[-1]
data[b,(cols) := mget(cols), on = "ref"][]

     ref  names    radius     height      weight     volume      money
   <int> <char>     <num>      <num>       <num>      <num>      <num>
1:     1      a 0.9757437 -1.2441942 -0.19825867  0.7934811  0.6642228
2:     2      b 0.9752424  1.0112435 -1.27333411  0.9296093 -1.1942749
3:     3      c 0.6989610  0.8868158 -1.54361300 -0.4824725 -0.8368856
4:     4      d 0.4336850  0.8949459  1.45199656 -0.3262636 -0.5158351
5:     5      e 0.9989011  0.4237771  0.04365383 -1.4086310  0.7379102
6:     6      f 0.2640407 -2.0085267 -0.15621784  1.3278945  0.2616385

Upvotes: 3

Related Questions