samedi 9 novembre 2019

IF_ELSE statement not working as expected

I am trying to create a new variable based off a conditional evaluation of a number of other variables. I am using some nested "if_else" statements, but only part of the conditional statement is evaluating as I want it to.

Here is the dput for some sample data:

structure(list(`Cultivation` = c("No", "No", "Yes", 
"Yes", "No", "Yes", "No", "No", "No", "No", "Yes", "Yes"), 
`Processing` = c("No", 
"No", "Yes", "Yes", "No", "No", "No", "No", "No", "No", "No", 
"Yes"), `Federal Sales` = c("No", "No", "Yes", "Yes", "Yes", 
"Yes", "No", "No", "No", "No", "Yes", "Yes"), `Cultivation 
Type` = c(NA, 
NA, "Standard", "Standard", NA, "Micro", NA, NA, NA, NA, "Nursery", 
"Standard"), `Processing Type` = c(NA, NA, "Standard", 
"Standard", NA, NA, NA, NA, NA, NA, NA, "Standard"), `Type` = c(NA, 
NA, "Standard", "Standard", NA, "Micro", NA, NA, NA, NA, NA, 
"Standard")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-12L))

Here is the code I am using:

DF.2 <- DF.1 %>%
  dplyr::mutate("Type" = if_else(str_detect(tolower(`Cultivation Type`), 
"micro") |

str_detect(tolower(`Processing Type`), "micro"), "Micro",

if_else(str_detect(tolower(`Cultivation Type`), "standard") |

str_detect(tolower(`Processing Type`), "standard"), "Standard",

if_else(str_detect(tolower(`Cultivation Type`), "nursery"), 
"Nursery","Other"))))

The first two conditions are being met and I get a type variable of either "standard" or "micro", but "nursery" and "other" do not evaluate and I get "NA".

Aucun commentaire:

Enregistrer un commentaire