r %in% operator | control case sensitivity [duplicate]

我是研究僧i 提交于 2019-12-11 06:21:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!