Ifelse with several conditions for creating a new variable in data.table R

I have data.table and you want to create a new variable based on several conditions in the ifelse statement, but what I get as a result seems strange.

Imagine the following simplified example.

 DT <- data.table(replicate(2,sample(0:1,5,replace=TRUE))) V1 V2 1: 1 0 2: 1 1 3: 1 1 4: 1 0 5: 0 1 

I want to create a new variable based on existing variables. I use the ifelse statement as follows:

 DT[, new.var := ifelse(V1 > 0, 1, 0)] DT[, new.var.mult := ifelse(V1 > 0 && V2 > 0, 1, 0)] 

However, this does not work in the case of several conditions. (I know that this problem can be easily solved without many conditions, but my problem is more complicated.)

  V1 V2 new_var new_var_multiple 1: 1 0 1 0 2: 1 1 1 0 3: 1 1 1 0 4: 1 0 1 0 5: 0 1 0 0 

What could be the problem?

+6
source share
1 answer

To compare vectors, you should use only one ampersand (&).

 DT[, new.var.mult := ifelse(V1 > 0 & V2 > 0, 1, 0)] 

Illustration:

 > c(TRUE, TRUE) & c(FALSE, TRUE) [1] FALSE TRUE > c(TRUE, TRUE) && c(FALSE, TRUE) [1] FALSE 
+5
source

Source: https://habr.com/ru/post/981977/


All Articles