Reputation: 39
I am having some trouble with a nested ifelse statement. I have the following code written. It should force a TRUE or FALSE but I am getting some NAs. Can you help me figure out where its broken?
data looks something like...
Name<- c(Jon,Jim,Jake,Jess,Jill,Jay,Jason)
LinkFlag<- c( NA, NA, NA, NA, NA, NA, NA)
1<- c(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
2<- c(2.5, NA, NA, NA, NA, 3.0, NA)
spread_wide<-c(Name,LinkFlag,1,2)
The intended Result is that there are no NAs
sw_RESULTS$EvalSeq1to2<-ifelse(spread_wide$`1` == 99, TRUE,
ifelse(spread_wide$`1` == (spread_wide$`2`-1), TRUE,
ifelse(is.na(spread_wide$`2`),TRUE,
ifelse(spread_wide$`2` ==99,TRUE,
ifelse(spread_wide$`1`== (spread_wide$`2`-0.5),TRUE,
ifelse(spread_wide$`1` == spread_wide$`2`, TRUE,
ifelse(spread_wide$`LinkFlag`=='FlagforSkip", TRUE,
FALSE)))))))
Upvotes: 1
Views: 192
Reputation: 93813
You essentially have a set of binary checks that each return TRUE
, or FALSE
if none of them are true. So, it's simple then to just make a matrix
or list
of all the checks together:
checks <- with(spread_wide,
cbind(
`1` == 99,
`1` == `2` - 1,
is.na(`2`),
`2` == 99,
`1` == (`2` - 0.5),
`1` == `2`,
LinkFlag == 'FlagforSkip'
)
)
rowSums(checks, na.rm=TRUE) > 0
#[1] FALSE TRUE TRUE TRUE TRUE FALSE TRUE
The secret to the final line is using the na.rm=TRUE
so that you are never giving any consideration to comparisons like NA == 1
which will return NA
instead of TRUE
or FALSE
.
As a side-note, using variable names like 1
or 2
is just asking for trouble.
Reproducible data that works:
Name<- c("Jon","Jim","Jake","Jess","Jill","Jay","Jason")
LinkFlag<- c( NA, NA, NA, NA, NA, NA, NA)
`1` <- c(1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
`2` <- c(2.5, NA, NA, NA, NA, 3.0, NA)
spread_wide<- data.frame(Name,LinkFlag,`1`,`2`,check.names=FALSE)
Upvotes: 2