问题描述
利用以下示例数据,我试图基于三个条件变量(Denial1,Denial2和Denial3)的值创建一个新的变量"Den"(值"0"或"1").
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).
如果三个条件变量中的任何一个都具有"0"和"1",那么我想要一个"0",仅当每个条件变量中具有一个值的值具有"1"(例如,不是不适用).
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")
我已经尝试了以下两个命令,导致"Den"的值缺少NA:
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?
推荐答案
基于@jaimedash和@Old_Mortality的建议,我找到了一个解决方案:
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")
然后,如果条件变量的所有值均为NA,则确保NA的值:
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)
这篇关于R中具有多个条件的Ifelse语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!