Kumar Manglam
Kumar Manglam

Reputation: 2832

How to assign dynamic column names in data.table under `:=`?

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

Answers (1)

akrun
akrun

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

Related Questions