Enrique Pérez Herrero Enrique Pérez Herrero - 2 years ago 87
R Question

Select column using the value in other row of a data.table in R

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

depending on the value of another column, the example goes as follows:


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


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
where if column
is "X1" (or "X2") the content on the column
) 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.


Answer Source

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)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download