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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With