简体   繁体   中英

R case insensitive if check

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM