Turning off Case Sensitivity in R

I am having difficulty with case sensitivity. Can we turn it off?

A1 <- c("a", "A", "a", "a", "A", "A", "a")
B1 <- c(rep("a", length(A1)))

A1 == B1
# [1]  TRUE FALSE  TRUE  TRUE FALSE FALSE  TRUE

should be all TRUE

2 Answers

There's no way to turn off case sensitivity of ==, but coercing both character vectors to uppercase and then testing for equality amounts to the same thing:

toupper(A1)
[1] "A" "A" "A" "A" "A" "A" "A"

toupper(A1)==toupper(B1)
# [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE

As Josh O'Brien said. To extend a bit on caseless matching in R, that is actually possible with regular expressions (using eg grep and grepl)

In this case you could use mapply and grepl like this, provided you're matching single characters :

A1 <- c("a", "A", "a", "a", "A", "A", "a")
B1 <- c(rep("a", length(A1)))

mapply(grepl,A1,B1,ignore.case=TRUE)
#    a    A    a    a    A    A    a 
# TRUE TRUE TRUE TRUE TRUE TRUE TRUE 

You have to be careful though, because it also matches partial strings like this :

C1 <- rep('ab',length(A1))
mapply(grepl,A1,C1,ignore.case=TRUE)
#    a    A    a    a    A    A    a 
# TRUE TRUE TRUE TRUE TRUE TRUE TRUE  

This may or may not be what you want.

On a sidenote, if you match with regular expressions and you want to ignore the case, you can also use the construct (?i) to turn on caseless matching and (?-i) to turn off caseless matching :

D1 <- c('abc','aBc','Abc','ABc','aBC')

grepl('a(?i)bc',D1) # caseless matching on B and C
# [1]  TRUE  TRUE FALSE FALSE  TRUE

grepl('a(?i)b(?-i)c',D1) # caseless matching only on B
# [1]  TRUE  TRUE FALSE FALSE FALSE
5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest