Consider below expression:
x$Y = ifelse(x$A<= 5 & abs(x$B) >= 2,
ifelse(x$B> 2 ,"YES","NO"),
'NA')
What I understand is that, if A is <=5 and B >=2 then ALL are YES, if not then NO, but I am confused the second ifelse
condition. Any help will be highly appreciated.
Thanks
CodePudding user response:
If we rewrite your ifelse
expression using expanded syntax, it might be easier to understand.
x$Y <- ifelse(x$A <= 5 & abs(x$B) >= 2, ifelse(x$B > 2, "YES", "NO"), 'NA')
# becomes
if (x$A <= 5 & abs(x$B) >= 2) {
if (x$B > 2) {
x$Y <- "YES"
} else {
x$Y <- "NO"
}
} else {
x$Y <- NA
}
The second nested ifelse()
corresponds to the inner if
above. It checks the value of x$B
to see if it be greater than 2, or less than -2 (one of these much be the case based on the earlier check abs(x$B) >= 2
. If the former be the case, then x$Y
gets assigned to YES
, otherwise it gets assigned to NO
.
CodePudding user response:
This code aims to define a new column, Y
in the data set x
. The column Y
will populate based on the following statements: