How can I add the columns a, b, c contained in new_cols to data.table df with the value NA? Preferably a nice solution without a loop.
df <- data.table(iris)
new_cols <- c("a", "b", "c")
The data.table syntax would be to assign (:=) the NA to the column names specified in the object 'new_cols'
library(data.table)
df[, (new_cols) := list(NA)]
-output
> head(df)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species a b c
1: 5.1 3.5 1.4 0.2 setosa NA NA NA
2: 4.9 3.0 1.4 0.2 setosa NA NA NA
3: 4.7 3.2 1.3 0.2 setosa NA NA NA
4: 4.6 3.1 1.5 0.2 setosa NA NA NA
5: 5.0 3.6 1.4 0.2 setosa NA NA NA
6: 5.4 3.9 1.7 0.4 setosa NA NA NA