0
votes

I am having some trouble debugging my nested ifelse statement.

It runs the first part just fine, then won't run the second ifelse statement. I have tried reversing the order of the statements. I have several functions that work similarly. I don't understand why the second half is not running like it's supposed to.

If math, read, write are all read "pass", then the element in the Result vector should be "Pass", if there is a"yes" Exempt column then the element in the result vector should be "Exempt" everything else should read "Not Pass".

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"))
1
Hi, we can't do much with your code if you don't provide any data. - jay.sf
You're still missing dat$Math and Praxis_Dat from your example - divibisan
Note: your posted example data is not a data frame but a character matrix. Once you clear that up and fix case-sensitive and spelling of columns, there is no issue: rextester.com/WQJRU6005. - Parfait

1 Answers

0
votes

The nested ifelse is fine:

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+

However, your Praxis_Dat[, 22:24] == "Pass" might to be the issue. It is not clear what this means? At least not when you do not provide any data.

The analogous code here works as I would expect, but what is your expected output in this case?

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-"

Of course, you need to be careful when you assign this matrix output to a column:

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-