turning off case sensitivity in r

后端 未结 2 1233
有刺的猬
有刺的猬 2021-02-05 03:24

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


        
相关标签:
2条回答
  • 2021-02-05 04:10

    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
    
    0 讨论(0)
  • 2021-02-05 04:12

    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
    
    0 讨论(0)
提交回复
热议问题