I have a data.table DT, which contains 2 columns.
library(data.table)
DT = data.table(a = c(1, 2), b = c(2, 3))
I have a variable, named i
i <- "A"
Now I want to use i
to determine how to create a new column in data.table. If i == "A"
, I want to create a new column, which is a*b
.
However, if I use DT[ , NEW := ifelse(i == "A", a*b, a)]
The result is in below, which is not what I want.
a b NEW
1: 1 2 2
2: 2 3 2
The result that I am looking for is
a b NEW
1: 1 2 2
2: 2 3 6
I know if I generate a new column named i, I can get what I want.
DT[ , i := i]
DT[ , NEW := ifelse(i == "A", a*b, a)]
a b i NEW
1: 1 2 A 2
2: 2 3 A 6
Is there a simple way to reference variable i
, without generating a new column named i
?
Thanks