Using if else statement for multiple conditions
This can be done using either ifelse
with(dat, ifelse(x < 0.15 & dif <0, 3, ifelse(x > 0.15 & dif < 0, 2, 1)))
Or
with(dat, as.numeric(factor(1+4*(x < 0.15 & dif < 0) + 2*(x>=0.15 & dif < 0))))
The problem with your statement is that if
only checks the first element of the expression tested -- you should have received a warning. ifelse
is vectorized.
In addition, you can perform the tests in the reverse order for a simpler, equivalent expression:
with(dat,
ifelse(dif >= 0 , 1 , ifelse(x < 0.15, 3, 2))
)