Enrique Pérez Herrero - 2 months ago 8

R Question

I need to create a new variable containing the value in one column in a

`data.frame`

`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`

`Z`

`X1`

`X2`

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

Answer

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)]
```