1

Following up on this question, how would you assign values to multiple columns in a data table using the ":=" sign?

For example:

x <- data.table(a = 1:3, b = 1:6, c = 11:16) 

I can get what i want using two lines:

x[a>2, b:=NA]
x[a>2, c:=NA]

but would like to be able to do it in one, something like this:

x[a>2, .(b:=NA, c:=NA)]

But unfortunately that doesn't work. Is there another way?

Jeppe Olsen
  • 968
  • 8
  • 19

1 Answers1

2

We can use the := once with

x[a >2, `:=`(b = NA, c = NA)]

If there are many columns, another option is set

for(nm in names(x)[-1]) set(x,  i=which(x[["a"]]>2), j=nm, value = NA)
akrun
  • 874,273
  • 37
  • 540
  • 662