Ifelse statement in R with multiple conditions

耗尽温柔 提交于 2021-02-18 09:28:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!