问题
Is there a way to control the case sensitivity of the %in% operator? In my case I want it to return true no matter the case of the input:
stringList <- c("hello", "world")
"Hello" %in% stringList
"helLo" %in% stringList
"hello" %in% stringList
Consider this code as a reproducible example, however in my real application I am also using a list of strings on the left and check for the presence of words from stringList.
回答1:
Use grepl
instead as it has an ignore.case
parameter:
grepl("^HeLLo$",stringList,ignore.case=TRUE)
[1] TRUE FALSE
The first argument is a regular expression, so it gives you more flexibility, but you have to start with ^
and end with $
to avoid picking up sub-strings.
回答2:
In addition to @James's answer, you can also use tolower
if you want to avoid regexes:
tolower("HeLLo") %in% stringlist
If left side is also a character vector then we make tolower both sides, e.g.:
x <- c("Hello", "helLo", "hello", "below")
stringList <- c("heLlo", "world")
tolower(x) %in% tolower(stringList)
# [1] TRUE TRUE TRUE FALSE
来源:https://stackoverflow.com/questions/40174604/r-in-operator-control-case-sensitivity