【问题标题】:Words matching in two columns using r使用 r 在两列中匹配的单词
【发布时间】:2016-11-09 10:21:38
【问题描述】:

我有两个数据框,其中 DF1 是(字典),DF2 是句子。我想以这样的方式进行文本匹配,如果 DF1 中的单词与 DF2 句子匹配(句子中的任何单词),那么输出应该是如果匹配则为是或如果不匹配数据框则为否的列如下:

(DF1)词典:

DF1 <- c("csi", "dsi", "market", "share", "improvement", "dealers", "increase")

(DF2)句子:

DF2 <- c("Customer satisfaction index improvement", "reduction in retail cycle", "Improve market share", "% recovery from vendor")

输出应该是:

客户满意度指数提升(是)

零售周期缩短(否)

提高市场份额(是)

从供应商处回收的百分比(否)

注意-是和否是显示文本匹配结果的不同列 任何人都可以帮助.....提前谢谢

【问题讨论】:

  • 请调整您的问题以包含两个数据集,其格式可以复制粘贴以及最终结果,否则很难回答您的问题。
  • DF1 是第一个数据框,如果是第二个数据框,则为 DF2,如果 df2 的第一行是客户满意度指数改进,则输出应该是这样,则显示是
  • 是的,是的,我明白这一点,但它不是一种格式,有人可以轻松地复制并粘贴到他的 R 会话中以寻找答案。您可以尝试放置 dput(DF1) 或类似的东西以使其更容易。更多详情请看这里:stackoverflow.com/questions/5963269/…
  • df1
  • 看看答案告诉我

标签: r string data-manipulation


【解决方案1】:

你可以这样做:

df <- data.frame(sentence = c("Customer satisfaction index improvement", "reduction in retail cycle", "Improve market share", "% recovery from vendor"))
words <- c("csi", "dsi", "market", "share", "improvement", "dealers", "increase")

# combine the words in a regular expression and bind it as column yes
df <- cbind(df, yes = grepl(paste(words, collapse = "|"), df$sentence))


这输出
                                 sentence   yes
1 Customer satisfaction index improvement  TRUE
2               reduction in retail cycle FALSE
3                    Improve market share  TRUE
4                  % recovery from vendor FALSE

working on ideone.com

【讨论】:

  • @Roshan:那么请提供更多输入。
【解决方案2】:

试试这个:

DF1 <- c("csi", "dsi", "market", "share", "improvement", "dealers", "increase")
DF2 <- c("Customer satisfaction index improvement", "reduction in retail cycle", "Improve market share", "% recovery from vendor")


result <- cbind(DF2, "word found" = ifelse(rowSums(sapply(DF1, grepl, x = DF2)) > 0, "YES", "NO"))

> result
     DF2                                       word found
[1,] "Customer satisfaction index improvement" "YES"     
[2,] "reduction in retail cycle"               "NO"      
[3,] "Improve market share"                    "YES"     
[4,] "% recovery from vendor"                  "NO"    

【讨论】:

  • 当我将它应用到完整的数据集时,它只在输出中显示“是”
  • 这是什么意思?我猜你的完整数据集只包含 DF1 中的更多单词或 DF2 中的更多句子,在任何一种情况下都不应该有任何变化。
  • DF1 包含更多单词作为其词典,DF2 是句子中的描述,我只是给出了它的示例,因为我无法在此处粘贴完整的数据
  • 是的,我明白你的意思。我能想到的唯一原因是来自单词或句子的数据不是矢量格式。难道你只有一根大绳子吗?请粘贴 str(DF2) 和 str(DF1) 的结果
  • 您能分享您的电子邮件ID吗?我将在excel文件中向您发送示例数据框
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 2011-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-23
相关资源
最近更新 更多