如何创建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)]
没有运气。
我也看过并阅读this question,但无法让这个解决方案适合我。
答案 0 :(得分:1)
> dt[, paste("cap", names(dt), sep=""):= pmin(3, DeltaPaid)]
> dt
DeltaPaid capDeltaPaid
1: 1 1
2: 2 2
3: 4 3
4: 8 3
如果这是针对多个列,那么在&#34;内部图像&#34;上使用lapply实施相同的策略。 (或.SD
的真实姓名):
> 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