【发布时间】:2018-08-17 19:35:58
【问题描述】:
我有一个数据框,我需要在其中比较两列并找到两个元素之间匹配字符的数量。
例如:x 和 y 是要比较的两个元素,如下所示:
x<- "1/2"
y<-"2/3"
我没有列出它们,并用“/”将它们分开,如下所示:
unlist(strsplit(x,"/"))->a
unlist(strsplit(y,"/"))->b
然后我使用了pmatch:
pmatch(a,b,nomatch =0)
[1] 0 1
使用 sum() 知道有多少个字符匹配:
sum(pmatch(a,b,nomatch =0))
[1] 1
但是,当以其他方式进行比较时:
pmatch(b,a,nomatch = 0)
[1] 2 0
既然两个字符串之间只有一个匹配,为什么它显示2。可能是索引。但是我需要得到字符串之间有多少个字符是相同的,而不管比较 a vs b 或 b vs a。
有人可以帮助如何获得这个。
【问题讨论】:
-
阅读
?pmatch,特别是返回值——它是一个整数向量,给出了表中匹配的元素的索引。所以不要求和,试试length(pmatch(a,b)) -
也许:
length(intersect(a, b))
标签: r string string-comparison