r - data.table column name and definition defined by variable -


this question has answer here:

how create data.table column, name , column definition determined variable?

in case, 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 variable cap passed 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, column name paste("deltapaid.capped.",cap,sep="") , column definition 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 seen , read through this question unable solution work me.

> dt[, paste("cap", names(dt), sep=""):= pmin(3, deltapaid)] > dt    deltapaid capdeltapaid 1:         1            1 2:         2            2 3:         4            3 4:         8            3 

if multiple columsn same strategy implemented lapply on "interior image" (or whatever real name of .sd might be):

> dt[, paste("cap", names(dt), sep=""):= lapply(.sd, function(x) {pmin(3, x)})] > dt    deltapaid capdeltapaid capcapdeltapaid 1:         1            1               1 2:         2            2               2 3:         4            3               3 4:         8            3               3 > dt[, paste("cap", names(dt), sep=""):= lapply(.sd, function(x) {pmin(3, x)})] > dt    deltapaid capdeltapaid capcapdeltapaid capcapcapdeltapaid 1:         1            1               1                  1 2:         2            2               2                  2 3:         4            3               3                  3 4:         8            3               3                  3 

Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -