Sebastian Zeki
Sebastian Zeki

Reputation: 6874

ifelse returning NAs when condition is true

I am missing something fundamental here. I want to extract strigns from a dataframe based on nested ifelse

Input

library(stringr)
vec1<-c("1cm start shaped area Barr.","small tongue of columnar lines mucosa in the.")

vec1<-data.frame(vec1,stringsAsFactors = FALSE)

Attempt

ifelse(grepl("Barr|column",vec1$vec1),str_extract(vec1$vec1,"\\d\\s*cm.*Barr|column\\?//."),
           ifelse(grepl("Barr|column",vec1$vec1),str_extract(vec1$vec1,"tongue.*col"),"No"))

Desired output

"1cm start shaped area Barr"
"tongue of col"

Actual output

[1] "1cm start shaped area Barr" NA  

Why are the two conditions not being met and extracted?

I will go on to use case_when with dplyr as an alternative I guess but I'd like to understand the problem with the ifelse (and why case_when might be different to ifelse

Upvotes: 0

Views: 113

Answers (1)

duckmayr
duckmayr

Reputation: 16920

Your first condition (which is weirdly identical to the second I think?) is TRUE for both elements, but the extraction of the first pattern is NA for the second element:

library(stringr)
vec1 <- c("1cm start shaped area Barr.","small tongue of columnar lines mucosa in the.")

vec1 <- data.frame(vec1,stringsAsFactors = FALSE)

grepl("Barr|column", vec1$vec1)
#> [1] TRUE TRUE
str_extract(vec1$vec1, "\\d\\s*cm.*Barr|column\\?//.")
#> [1] "1cm start shaped area Barr" NA

Created on 2018-12-08 by the reprex package (v0.2.1)

You could of course instead give a vector for the pattern argument of str_extract() if your two ifelse() conditions are indeed supposed to be identical:

library(stringr)
vec1 <- c("1cm start shaped area Barr.","small tongue of columnar lines mucosa in the.")

vec1 <- data.frame(vec1,stringsAsFactors = FALSE)

grepl("Barr|column", vec1$vec1)
#> [1] TRUE TRUE
str_extract(vec1$vec1, "\\d\\s*cm.*Barr|column\\?//.")
#> [1] "1cm start shaped area Barr" NA
ifelse(grepl("Barr|column", vec1$vec1),
       str_extract(vec1$vec1, c("\\d\\s*cm.*Barr|column\\?//.", "tongue.*col")),
       "No")
#> [1] "1cm start shaped area Barr" "tongue of col"

Created on 2018-12-08 by the reprex package (v0.2.1)

Upvotes: 2

Related Questions