turning off case sensitivity in r

后端 未结 2 1244
有刺的猬
有刺的猬 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
    

提交回复
热议问题