r - Operations on data table with variable column name -
i trying perform operations on data.table
's column passed variable.
here toy example:
library(data.table) set.seed(2) dt <- data.table(replicate(3, runif(4))) > dt v1 v2 v3 1: 0.1848823 0.9438393 0.4680185 2: 0.7023740 0.9434750 0.5499837 3: 0.5733263 0.1291590 0.5526741 4: 0.1680519 0.8334488 0.2388948
say column of interest passed value of variable:
> print(target.column <- sample(colnames(dt), 1)) [1] "v3"
so perform operation on column v3
, say, flooring value @ 0.5 simplicity. have made work using dreaded paste
, parse
, eval
:
> eval(parse(text = paste0("dt[", target.column, " < 0.5, ", target.column, " := 0.5, ]"))) v1 v2 v3 1: 0.1848823 0.9438393 0.5000000 2: 0.7023740 0.9434750 0.5499837 3: 0.5733263 0.1291590 0.5526741 4: 0.1680519 0.8334488 0.5000000
but have been unsuccessful in other attempts:
> dt[eval(target.column) < 0.5, eval(target.column) := 0.5, ] v1 v2 v3 1: 0.1848823 0.9438393 0.4680185 2: 0.7023740 0.9434750 0.5499837 3: 0.5733263 0.1291590 0.5526741 4: 0.1680519 0.8334488 0.2388948 > dt[as.name(target.column) < 0.5, as.name(target.column) := 0.5, ] v1 v2 v3 1: 0.1848823 0.9438393 0.4680185 2: 0.7023740 0.9434750 0.5499837 3: 0.5733263 0.1291590 0.5526741 4: 0.1680519 0.8334488 0.2388948 > dt[deparse(substitute(target.column)) < 0.5, deparse(substitute(target.column)) := 0.5, ] v1 v2 v3 1: 0.1848823 0.9438393 0.4680185 2: 0.7023740 0.9434750 0.5499837 3: 0.5733263 0.1291590 0.5526741 4: 0.1680519 0.8334488 0.2388948
i have looked solutions on , ol' interweb have not been able find useful... there "data.table" way this?
you can use
dt[ get(target.column) < .5, (target.column) := .5]
which gives desired result.
Comments
Post a Comment