Reputation: 512
I am wondering how I can replace the values in multiple columns simultaneously in a data.table.
Something like the following:
fake_DT <- data.table(iter = 1:5, A = 0, B = 0, C =0)
vec = c(1,2,3)
fake_DT[iter == 1, c("A", "B", "C") := vec]
Thanks!
Upvotes: 2
Views: 322
Reputation: 887118
We can convert the vector
to list
with as.list
as data.frame/data.table/tibble
etc are all list
with columns as elements and having some additional attributes
fake_DT[iter == 1, c("A", "B", "C") := as.list(vec)]
-ouptut
fake_DT
iter A B C
1: 1 1 2 3
2: 2 0 0 0
3: 3 0 0 0
4: 4 0 0 0
5: 5 0 0 0
In the data.table
syntax`, when we use
dt[, c('col1', 'col2' ) := .(5, 3)]`
the .(
is a compact way to specify list(5, 3)
Upvotes: 4