turning off case sensitivity in r

女生的网名这么多〃 提交于 2019-12-20 11:09:17

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/8361589/turning-off-case-sensitivity-in-r

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