繁体   English   中英

如何比较R中的两个字符串?

[英]How to compare two strings in R?

我在比较 R 中的两个字符串时遇到问题。有没有办法做到这一点?

就像在 Java 中你有String.equals(AnotherString) ,在 R 中是否有类似的 function?

其实很简单。

s1 <- "string"
s2 <- "String"

# Case-sensitive check
s1 == s2

# Case-insensitive check
tolower(s1) == tolower(s2)

第一种情况下的输出为FALSE ,第二种情况下为TRUE 您也可以使用toupper()

您可以使用str_equal stringr 1.5.0中的 str_equal 。 它包括一个ignore_case参数:

library(stringr)
s1 <- "string"
s2 <- "String"

str_equal(s1, s2)
#[1] FALSE

str_equal(s1, s2, ignore_case = TRUE)
#[1] TRUE

str_equal使用Unicode 规则来比较字符串,这在某些情况下可能是有益的:

a1 <- "\u00e1"
a2 <- "a\u0301"
c(a1, a2)
#[1] "á" "á"

a1 == a2
#[1] FALSE
str_equal(a1, a2)
#[1] TRUE

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM