【发布时间】:2020-10-14 13:04:08
【问题描述】:
我有一个 R data.table 的大量列名(变量)列表,我想创建一个包含这些列的乘积的列。
例子:
col_names <- c("season_1","season_2","season_3")
DT_example <- data.table(id=1:4,
season_1=c(1,1,0,0),
season_2=c(0,1,1,1),
season_3=c(1,0,1,0),
product=1)
数据表:
id season_1 season_2 season_3 product
1: 1 1 0 1 1
2: 2 1 1 1 1
3: 3 0 1 1 1
4: 4 0 1 0 1
我的解决方案是使用“for”循环,但效率不高:
for(inc in col_names){
nm1 <- as.symbol(inc)
DT_example[,product:= product * eval(nm1)]
}
结果:
id season_1 season_2 season_3 product
1: 1 1 0 1 0
2: 2 1 1 0 0
3: 3 1 1 1 1
4: 4 0 1 0 0
有没有更快的方法使用 data.table 原生语法来做到这一点?
【问题讨论】:
-
DT_example[, product := Reduce("*", .SD), .SDcols = col_names] -
显示的示例数据和重现它的代码不匹配。
标签: r data.table