如何在R中比较字符串(3个例子)

924 阅读2分钟

你可以使用以下方法来比较R中的字符串。

方法1:比较两个字符串

#case-sensitive comparison
string1 == string2

#case-insensitive comparison
tolower(string1) == tolower(string2)

方法2:比较两个字符串的矢量

#case-sensitive comparison
identical(vector1, vector2)

#case-insensitive comparison
identical(tolower(vector1), tolower(vector2))

方法3:寻找两个字符串向量之间的相似性

#find which strings in vector1 are also in vector2
vector1[vector1 %in% vector2]  

下面的例子说明了如何在实践中使用每种方法。

例1:检查两个向量是否相同

下面的代码显示了如何在R中比较两个字符串以确定它们是否相等:

#define two strings
string1 <- "Mavericks"
string2 <- "mavericks"

#case-sensitive comparison
string1 == string2

[1] FALSE

#case-insensitive comparison
tolower(string1) == tolower(string2)

[1] TRUE

由于这两个字符串不是完全相同的,所以区分大小写的比较会返回一个FALSE的值。

然而,不区分大小写的比较返回值为"true",因为这两个字符串以相同的顺序包含相同的字符,不分大小写。

例2:比较两个字符串的矢量

下面的代码显示了如何使用identical()函数来确定两个字符串向量是否相等:

#define two vectors of strings
vector1 <- c("hey", "hello", "HI")
vector2 <- c("hey", "hello", "hi")

#case-sensitive comparison
identical(vector1, vector2)

[1] FALSE

#case-insensitive comparison
identical(tolower(vector1), tolower(vector2))

[1] TRUE

对大小写敏感的比较会返回一个FALSE值,因为这两个向量在相同的情况下不包含完全相同的字符串。

然而,不区分大小写的比较返回值为**"true"**,因为这两个向量包含相同的字符串,无论大小写如何。

例3:寻找两个字符串向量之间的相似性

下面的代码显示了如何使用%in%操作符来查找一个向量中的哪些字符串属于另一个向量:

#define two vectors of strings
vector1 <- c("hey", "hello", "greetings")
vector2 <- c("hey", "hello", "hi")

#find which strings in vector1 are also in vector2
vector1[vector1 %in% vector2]

[1] "hey"   "hello"

从输出结果中我们可以看到,字符串 "hey "和 "hello "同时存在于向量1和向量2中。

相关的 如何在R中使用%in%操作符

其他资源

下面的教程解释了如何在R中执行其他常见的操作:

如何在R中比较两列
如何在R中比较两个向量
如何在R中查找字符串中的字符位置
如何在R中把向量转换为字符串