9

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?

user438383
  • 5,716
  • 8
  • 28
  • 43
Kevin L Xu
  • 158
  • 1
  • 2
  • 8
  • 5
    You can check with `==` or `all.equal` or `identical` – akrun Feb 08 '20 at 19:55
  • 1
    In addition to the above, would encourage you to edit your question and show us what your strings look like and what you tried so far. Please see: [how to make a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Ben Feb 08 '20 at 20:07
  • This [blog](https://www.r-bloggers.com/2022/01/how-to-compare-strings-in-r-with-examples/) has several ways to compare strings based on what your strings look like. – close2zero Jun 08 '23 at 14:53

2 Answers2

15

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.

RD_
  • 315
  • 2
  • 5
3

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
Maël
  • 45,206
  • 3
  • 29
  • 67