Reputation: 2832
Consider the below code :
library(data.table)
carsDT <- data.table(cars)
carsDT[speed < 15, `:=`(paste0("col", 1)=1 paste0("col", 2)=2)]
This code gives the error :
Error: unexpected '=' in "carsDT[speed < 15, `:=`(paste0("col", 1)="
Is there any way, that inside :=
, I can use dynamic column names? I know that I can do above like this :
carsDT[speed < 15, (paste0("col", 1)) := 1]
carsDT[speed < 15, (paste0("col", 2)) := 2]
This solution will involve many lines of code(number of columns to be assigned is in 100s). It will be convenient if I can do all the assignments under single :=
.
Any help is appreciated.
Upvotes: 3
Views: 227
Reputation: 887088
We can place the values in a list
or use .(...)
and then assign (:=
) it to new columns
carsDT[speed < 15, paste0("col", 1:2) := list(1, 2)]
Upvotes: 4