首页 > 解决方案 > 大型数据集 R 的两列之间的部分字符串匹配

问题描述

我有两列,如果两列之间存在部分匹配,我想创建一个二进制列。
例如:

X             Y        Match
hello         hello     1
hi hello      hi        1
NA            bye       NA
bye           hi bye    1
good          bad       0

我使用了以下代码,

df['Match'] <- ifelse(with(df, str_detect(x, y)|str_detect(y, x)), 1, 0)

这适用于前几行,但是当我在整个数据集(n = 14000)上使用它时,我不断收到此错误:

Error in stri_detect_regex(string, pattern, opts_regex = opts(pattern)) :
Incorrectly nested parentheses in regexp pattern. (U_REGEX_MISMATCHED_PAREN)

我应该如何解决这个问题?

标签: r

解决方案


您的数据中可能有括号或导致此错误的特殊字符。

尝试这样的循环:

for(i in 1:nrow(df)) {
  print(i)
  str_detect(df$x[i], df$y[i])
}

最后i打印的将告诉您问题出在哪一行。


推荐阅读