Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ifelse with multiple condition for creating new variable in data.table R [duplicate]

I have a data.table and want to create a new variable based on multiple conditions in an ifelse statement but what I get as a result seems to be strange.

Let's 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 the 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 case of multiple conditions. (I am aware that this task could be solved easily without multiple condition 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 here?

like image 915
janosdivenyi Avatar asked Feb 04 '15 13:02

janosdivenyi


1 Answers

You have to use only one ampersand (&) to compare vectors.

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
like image 178
Marcel Hebing Avatar answered Sep 28 '22 12:09

Marcel Hebing