I have a large list of column names (variables) of an R data.table and I want to create a column containing the product of these columns.
Example:
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)
data.table:
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
The solution I have is using a "for" loop but it is not very efficient:
for(inc in col_names){
nm1 <- as.symbol(inc)
DT_example[,product:= product * eval(nm1)]
}
result:
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
Is there a faster way to do this using data.table native syntax?
DT_example[, product := Reduce("*", .SD), .SDcols = col_names]- Roland