I'm having trouble comparing two strings in R. Is there a method to do it?
Like in Java you have String.equals(AnotherString), is there a similar function in R?
I'm having trouble comparing two strings in R. Is there a method to do it?
Like in Java you have String.equals(AnotherString), is there a similar function in R?
 
    
     
    
    It's pretty simple actually.
s1 <- "string"
s2 <- "String"
# Case-sensitive check
s1 == s2
# Case-insensitive check
tolower(s1) == tolower(s2)
The output in the first case is FALSE and in the second case it is TRUE. You can use toupper() as well.
 
    
    You can use str_equal from stringr 1.5.0. It includes an ignore_case argument:
library(stringr)
s1 <- "string"
s2 <- "String"
str_equal(s1, s2)
#[1] FALSE
str_equal(s1, s2, ignore_case = TRUE)
#[1] TRUE
str_equal uses the Unicode rules to compare strings, which might be beneficial in some cases:
a1 <- "\u00e1"
a2 <- "a\u0301"
c(a1, a2)
#[1] "á" "á"
a1 == a2
#[1] FALSE
str_equal(a1, a2)
#[1] TRUE
