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)))
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
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