2

I have a data.table DT with 2 columns: ID, QTY

     ID        QTY
    000001       0
    000002       1
    000002       2
    000004       0
    000005       1
    000006       2

I want to update the Qty column for those rows where Qty is greater than 1 and replace the corresponding Qty value with 1. This is a trivial task that can be performed by using sapply or simply using which command on the column. But I want to know if this can be achieved using the data.table[i,j,by/keyby,.SD] options.

Expected Output:

     ID        QTY
    000001       0
    000002       1
    000002       1
    000004       0
    000005       1
    000006       1

1 Answer 1

3

We can do this by converting the logical vector to binary with as.integer

DT[, QTY := as.integer(QTY>0)]
DT
#   ID QTY
#1:  1   0
#2:  2   1
#3:  2   1
#4:  4   0
#5:  5   1
#6:  6   1

Or specify it in the i and update the 'QTY'

DT[QTY>0, QTY := 1]
Sign up to request clarification or add additional context in comments.

5 Comments

does this operator ":=" has a special name? I could not find it in the vignette for introduction to data.table.
@Tushar It is the assignment operator
@DavidArenburg Will check this out too. Thanks a lot.
@DavidArenburg the link is broken.

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.