问题
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?
回答1:
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)
回答2:
How about?
DF$Den<-ifelse (is.na(DF$Denial1) | is.na(DF$Denial2) | is.na(DF$Denial3), "0", "1")
回答3:
There is a simpler solution to this. What you describe is the natural behavior of the &
operator and can thus be done primatively:
> c(1,1,NA) & c(1,0,NA) & c(1,NA,NA)
[1] TRUE FALSE NA
If all are 1, then 1 is returned. If any are 0, then 0. If all are NA, then NA.
In your case, the code would be:
DF$Den<-DF$Denial1 & DF$Denial2 & DF$Denial3
In order for this to work, you will need to stop working in character
and use numeric
or logical
types.
回答4:
Very simple use of any
df <- <your structure>
df$Den <- apply(df,1,function(i) {ifelse(any(is.na(i)) | any(i != 1), 0, 1)})
回答5:
another solution using dplyr is:
df <- ## your data ##
df <- df %>%
mutate(Den = ifelse(any(is.na(Den)) | any(Den != 1), 0, 1))
来源:https://stackoverflow.com/questions/36362573/ifelse-statement-in-r-with-multiple-conditions