YYY
YYY

Reputation: 625

How to replace value in multiple values?

I am new to the data.table. I just know how to replace value column by column. Is there any way to do it by 1 command? Here my sample code:

DT1 = data.table(A=sample(3, 10, TRUE), 
             B=sample(3, 10, TRUE),
             C=sample(3, 10, TRUE))

DT1[,A:=ifelse(A>1,1,0),]
DT1[,B:=ifelse(B>1,1,0),]
DT1[,C:=ifelse(C>1,1,0),]

Ideally there is a way to merge the last 3 command into 1. Thanks in advance.

Upvotes: 2

Views: 126

Answers (2)

Arun
Arun

Reputation: 118889

The most efficient (and idiomatic) way, is to use set() along with a for-loop here. set() is a low overhead version of := designed to handle repetitive cases like this.

for (cols in c("A", "B", "C")) {
    set(DT1, i=which(DT1[[cols]] > 1L), j=cols, value=0L)
}

Note that @ColonelBeauvel's solution returns an entirely new data set just to replace some rows for those columns, which is what data.table tries to avoid!

Upvotes: 2

Colonel Beauvel
Colonel Beauvel

Reputation: 31181

Like this:

DT1[,lapply(.SD, function(u) ifelse(u>1,1,0))]

Upvotes: 2

Related Questions