r - 按元素比较两列

标签 r string match sapply

我有一个大数据集 df(354903 行),其中有两列名为 df$ColumnNamedf$ColumnName.1

head(df)
       CompleteName       CompleteName.1
1   Lefebvre Arnaud Lefebvre Schuhl Anne
1.1 Lefebvre Arnaud              Abe Lyu
1.2 Lefebvre Arnaud              Abe Lyu
1.3 Lefebvre Arnaud       Louvet Nicolas
1.4 Lefebvre Arnaud   Muller Jean Michel
1.5 Lefebvre Arnaud  De Dinechin Florent

我正在尝试创建标签以查看名称是否相同。 当我尝试一个小子集时它起作用 [如果它们相同则为 1,如果不同则为 0]:

> match(df$CompleteName[1], df$CompleteName.1[1], nomatch = 0)
[1] 0
> match(df$CompleteName[1:10], df$CompleteName.1[1:10], nomatch = 0)
[1] 0 0 0 0 0 0 0 0 0 0

但是一旦我抛出完整的列,它就会给我完全不同的值,这对我来说似乎是无稽之谈:

> match(df$CompleteName, df$CompleteName.1, nomatch = 0)
[1] 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101
[23] 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101
[45] 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101 101

我应该使用sapply吗?我没有弄清楚,我试过这个错误:

 sapply(df, function(x) match(x$CompleteName, x$CompleteName.1, nomatch = 0))

请帮忙!!!

最佳答案

来自 match 的手册页,

‘match’ returns a vector of the positions of (first) matches of its first argument in its second.

所以您的数据似乎表明“Lefebvre Arnaud”的第一个匹配项(第一个参数中的第一个位置)在第 101 行中。我相信您打算做的是一个简单的比较,所以这只是相等运算符 ==.

一些示例数据:

> a <- rep ("Lefebvre Arnaud", 6)
> b <- c("Abe Lyu", "Abe Lyu", "Lefebvre Arnaud", rep("De Dinechin Florent", 3))
> x <- data.frame(a,b, stringsAsFactors=F)
> x
            a                   b
1 Lefebvre Arnaud             Abe Lyu
2 Lefebvre Arnaud             Abe Lyu
3 Lefebvre Arnaud     Lefebvre Arnaud
4 Lefebvre Arnaud De Dinechin Florent
5 Lefebvre Arnaud De Dinechin Florent
6 Lefebvre Arnaud De Dinechin Florent
> x$a == x$b
[1] FALSE FALSE  TRUE FALSE FALSE FALSE

编辑:此外,您需要确保您是在同类比较,因此请仔细检查列的数据类型。使用 str(df) 查看列是字符串还是因子。您可以使用“stringsAsFactors = FALSE”构造矩阵,或将因子转换为字符。有几种方法可以做到这一点,请在此处查看:Convert data.frame columns from factors to characters

关于r - 按元素比较两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36345915/

相关文章:

c# - c# 中的正则表达式找到字母然后\用大写字母作为字母和 Shift 按下其他字符的形式?

php - 删除标签但如果匹配字符串则保留标签之间的内容

r - 从列表中的 data.frame 中快速查找具有匹配元素名称的值

c - 字符串比较逻辑错误

mysql - 根据数据库中的关键字搜索 XML feed 的描述

r - 使用 bigmemory 和 irlba 对大矩阵进行 SVD 的问题

r - 在 R 中建立稀疏矩阵的更快方法?

r - 一次聚合多列

r - ggplot2 的特定条形图

php - 将 PHP 字符串变量添加到包含引号的文本框值