How do I create a data.table column, where the name and column definition are determined by a variable?
In my case, my data.table looks like
dt <- data.table(DeltaPaid = c(1,2,4,8))
dt
DeltaPaid
1: 1
2: 2
3: 4
4: 8
Now, if a variable cap
is passed as 3....
cap <- 3
dt[, DeltaPaid.capped.3:=pmin(3, DeltaPaid)]
dt
DeltaPaid DeltaPaid.capped.3
1: 1 1
2: 2 2
3: 4 3
4: 8 3
In other words, I would like the column name to be paste("DeltaPaid.capped.",cap,sep="")
and the column definition to be paste(":=pmin(",cap,", DeltaPaid)",sep="")
.
I tried
dt <- data.table(DeltaPaid = c(1,2,4,8))
cap <- 3
expr <- paste("DeltaPaid.capped.",cap,":=pmin(",cap,", DeltaPaid)",sep="")
dt[, eval(expr)]
with no luck.
I have also seen and read through this question but was unable to get that solution to work for me.