1

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.

florian
  • 604
  • 8
  • 31
  • Also, see [here](http://stackoverflow.com/questions/8361589/turning-off-case-sensitivity-in-r) and [here](http://stackoverflow.com/questions/27085620/which-command-in-r-with-case-insensitive). – zx8754 Oct 21 '16 at 11:39
  • Hmm I cannot see why this is a duplicate, however the posts you linked contain potential workarounds. – florian Oct 21 '16 at 13:05
  • It is not 100% duplicated as we are using `%in%` while linked post are using different functions, but check the answers, they are using the same "grepl with ignore case" and `tolower` or `toupper` functions to make it case-insensitive. – zx8754 Oct 21 '16 at 13:07
  • yes, but I would like to continue using %in%, maybe someone as a good solution for that..currently i think about converting both sides to lower/upper case – florian Oct 21 '16 at 13:10

2 Answers2

4

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.

James
  • 65,548
  • 14
  • 155
  • 193
  • Thank you James, what if the input on the left is also a list of strings? – florian Oct 21 '16 at 13:06
  • @florian You can use the or operator for regex, `|`. But it depends on how you want to handle multiple strings. – James Oct 21 '16 at 14:36
3

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
zx8754
  • 52,746
  • 12
  • 114
  • 209
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187