2

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!

1 Answer 1

4

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Can't believe I didn't try this one. Thank you! I will accept this answer after the waiting period has ended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.