Reputation: 480
What is the best way to create a case insensitive if statement?
For example if I have var = 'ignore'
if(var == 'Ignore'){print("pass")} else{print("fail")}
Will fail.
Some options that will pass include:
if(var == 'Ignore' | var == 'ignore' ){print("pass")} else{print("fail")}
if(tolower(var) == tolower('Ignore') ){print("pass")} else{print("fail")}
if(toupper(var) == toupper('Ignore') ){print("pass")} else{print("fail")}
Are there any other good options? Is there a best option(s)?
I'm not sure how "best" should be measured
Upvotes: 0
Views: 831
Reputation: 50668
We can also use grepl
with ignore.case = T
var <- "ignore"
if (grepl("Ignore", var, ignore.case = T)) "Pass" else "Fail"
#[1] "Pass"
Or using stringr::str_detect
with fixed(pattern, ignore_case = T)
library(stringr)
if (str_detect(var, fixed("Ignore", ignore_case = T))) "Pass" else "Fail"
#[1] "Pass"
Upvotes: 2