调试嵌套的ifelse语句时遇到麻烦。
它可以很好地运行第一部分,然后不会运行第二个ifelse
语句。我试图反转语句的顺序。我有几个功能相似。我不明白为什么下半场没有按预期运行。
如果数学,读,写都读为“通过”,则结果向量中的元素应为“通过”,如果有“是”豁免列,则结果向量中的元素应为“豁免”其他所有内容都应显示为“不及格”。
Math <-c("Pass", "Not Pass", "Not Pass", "NA", "NA", "NA")
Read<-c("Pass","Pass","Not Pass", "NA", "NA", "NA")
Write<-c("Pass","Pass", "Not Pass", "NA", "NA", "NA")
Exempt<-c( "NA", "NA", "NA","yes","yes","yes")
dat<-cbind(Math,Read,Write,Exempt)
dat$Result <-
ifelse(dat$math=="Pass" & dat$Read=="Pass" & dat$writing == "Pass",
"Pass",
ifelse(dat$Exempt == "yes", "Exempt", "Not Pass"))
答案 0 :(得分:0)
嵌套的ifelse
很好:
set.seed(2)
df <- data.frame(a = rnorm(10), b = rnorm(10))
df$c <- ifelse(df$a > 0, "a+", ifelse(df$b > 0, "b+", "b-"))
head(df)
# a b c
#1 -0.89691455 0.41765075 b+
#2 0.18484918 0.98175278 a+
#3 1.58784533 -0.39269536 a+
#4 -1.13037567 -1.03966898 b-
#5 -0.08025176 1.78222896 b+
#6 0.13242028 -2.31106908 a+
但是,您的Praxis_Dat[, 22:24] == "Pass"
可能是问题所在。目前尚不清楚这意味着什么?至少在您不提供任何数据时才不会。
此处的类似代码按我的预期工作,但是在这种情况下,您的预期输出是什么?
res <- ifelse(df[,1:2] > 0, "a+", ifelse(df$b > 0, "b+", "b-"))
head(res)
# a b
# [1,] "b+" "a+"
# [2,] "a+" "a+"
# [3,] "a+" "b-"
# [4,] "b-" "b-"
# [5,] "b+" "a+"
# [6,] "a+" "b-"
当然,在将此矩阵输出分配给列时,您需要小心:
df$d <- ifelse(df[,1:2] > 0, "a+", ifelse(df$b > 0, "b+", "b-"))
head(df)
# a b c d.a d.b
#1 -0.89691455 0.4176508 b+ b+ a+
#2 0.18484918 0.9817528 a+ a+ a+
#3 1.58784533 -0.3926954 a+ a+ b-
#4 -1.13037567 -1.0396690 b- b- b-
#5 -0.08025176 1.7822290 b+ b+ a+
#6 0.13242028 -2.3110691 a+ a+ b-