如何创建data.table列,其名称和列定义由变量确定?
就我而言,我的data.table看起来像
dt <- data.table(DeltaPaid = c(1,2,4,8))
dt
DeltaPaid
1: 1
2: 2
3: 4
4: 8
现在,如果将变量cap
作为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
换句话说,我希望列名称为paste("DeltaPaid.capped.",cap,sep="")
,列定义为paste(":=pmin(",cap,", DeltaPaid)",sep="")
。
我试过了
dt <- data.table(DeltaPaid = c(1,2,4,8))
cap <- 3
expr <- paste("DeltaPaid.capped.",cap,":=pmin(",cap,", DeltaPaid)",sep="")
dt[, eval(expr)]
没有运气。
我也已经阅读并阅读了这个问题,但是无法获得该解决方案对我有用。
> dt[, paste("cap", names(dt), sep=""):= pmin(3, DeltaPaid)]
> dt
DeltaPaid capDeltaPaid
1: 1 1
2: 2 2
3: 4 3
4: 8 3
如果这是针对多个列的,则对“内部图像”(或.SD
可能的真实名称)用lapply实施的相同策略:
> 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句