With the following sample data I'm trying to create a new variable "Den" (value "0" or "1") based on the values of three conditional variables (Denial1, Denial2, and Denial3).
I want a "0" if ANY of the three conditional variables has a "0" and a "1" only if EACH conditional variable that has a value in it has a value of "1" (e.g., isn't NA).
structure(list(Denial1 = NA_real_, Denial2 = 1, Denial3 = NA_real_, Den = NA), .Names = c("Denial1", "Denial2", "Denial3", "Den" ), row.names = 1L, class = "data.frame")
I've tried both of the following commands that result in a missing value NA for "Den":
DF$Den<-ifelse (DF$Denial1 < 1 | DF$Denial2 < 1 | DF$Denial3 < 1, "0", "1") DF$Den<-ifelse(DF$Denial1 < 1,"0", ifelse (DF$Denial2 < 1,"0", ifelse(DF$Denial3 < 1,"0", "1")))
Could someone demonstrate how to do this?
Multiple Conditions To join two or more conditions into a single if statement, use logical operators viz. && (and), || (or) and ! (not). && (and) expression is True, if all the conditions are true.
When you combine each one of them with an IF statement, they read like this: AND – =IF(AND(Something is True, Something else is True), Value if True, Value if False) OR – =IF(OR(Something is True, Something else is True), Value if True, Value if False) NOT – =IF(NOT(Something is True), Value if True, Value if False)
The multiple IF conditions in Excel are IF statements contained within another IF statement. They are used to test multiple conditions simultaneously and return distinct values. The additional IF statements can be included in the “value if true” and “value if false” arguments of a standard IF formula.
To run an if-then statement in R, we use the if() {} function. The function has two main elements, a logical test in the parentheses, and conditional code in curly braces. The code in the curly braces is conditional because it is only evaluated if the logical test contained in the parentheses is TRUE .
Based on suggestions from @jaimedash and @Old_Mortality I found a solution:
DF$Den <- ifelse(DF$Denial1 < 1 & !is.na(DF$Denial1) | DF$Denial2 < 1 & !is.na(DF$Denial2) | DF$Denial3 < 1 & !is.na(DF$Denial3), "0", "1")
Then to ensure a value of NA if all values of the conditional variables are NA:
DF$Den <- ifelse(is.na(DF$Denial1) & is.na(DF$Denial2) & is.na(DF$Denial3), NA, DF$Den)
How about?
DF$Den<-ifelse (is.na(DF$Denial1) | is.na(DF$Denial2) | is.na(DF$Denial3), "0", "1")
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