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?

1
  • 2
    You find the answer in the documentation help(':=') Commented Aug 20, 2018 at 14:16

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

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.