1

I need to create a new variable containing the value in one column in a data.frame depending on the value of another column, the example goes as follows:

library(data.table)

set.seed(pi)
DT <- data.table(
  X1 = LETTERS[1:10],
  X2 = letters[1:10],
  Z = sample(c("X1", "X2"), 10, replace = TRUE)
)

DT[]

This code generates the following

    X1 X2  Z
 1:  A  a X1
 2:  B  b X2
 3:  C  c X1
 4:  D  d X1
 5:  E  e X2
 6:  F  f X2
 7:  G  g X1
 8:  H  h X1
 9:  I  i X2
10:  J  j X2

Now I want to have a column W where if column Z is "X1" (or "X2") the content on the column X1 (or X2) is selected.

One solution can be:

DT[Z == "X1", W := X1]
DT[Z == "X2", W := X2]

But I would like to find a more elegant way to do this because I have many columns where I need to select one entry.

Thanks

Frank
  • 65,012
  • 8
  • 95
  • 173
Enrique Pérez Herrero
  • 3,248
  • 2
  • 30
  • 32

1 Answers1

2

We can use get after looping through sequence of rows

DT[, W :=  get(Z) , 1:nrow(DT)]

Or with eval(as.name

DT[,  W := eval(as.name(Z)) , 1:nrow(DT)]
akrun
  • 789,025
  • 32
  • 460
  • 575