【问题标题】:How to find that a word/words in a column is present in another column consisting a sentence [duplicate]如何找到一列中的一个单词/单词存在于另一个包含句子的列中[重复]
【发布时间】:2017-08-02 13:05:20
【问题描述】:

我期待一个 R 解决方案,它可以检查数据框的句子(第 2 列)中是否存在单词或句子(第 1 列)。如果句子中存在单词/单词,则应返回 1 (TRUE) 或 0 (FALSE)。 和

【问题讨论】:

  • 使用这个:stackoverflow.com/questions/26319567/… like grepl(gsub(" ", "|", "my new phone"), "this is my mobile phone")
  • 可能是mapply 和grepl?
  • 我尝试了 mapply() 和 grepl() 但它们只取子字符串 (column1) 的第一个单词来与字符串 (column2) 进行比较。

标签: r text


【解决方案1】:

这应该适合你:

df[, "lookup"] <- gsub(" ", "|", df[,"substring"])
df[,"t"] <- mapply(grepl, df[,"lookup"], df[,"string"])

df
#                 substring                 string                   lookup     t
#1             my new phone this is a mobile phone             my|new|phone  TRUE
#2 She would buy new phones Yes, I have two phones She|would|buy|new|phones  TRUE
#3            telephonessss       my old telephone            telephonessss FALSE
#4             telephone234           telephone234             telephone234  TRUE

您可以更喜欢创建查找列,但在这种情况下没有必要,所以我使用了一个简单的gsub。


数据:

df <- data.frame(substring = c("my new phone", "She would buy new phones", "telephonessss", "telephone234"),
                 string = c("this is a mobile phone", "Yes, I have two phones", "my old telephone", "telephone234"))

【讨论】:

    【解决方案2】:

    或者使用dplyr & stringr 解决方案。但原则上是相同的想法:

    library(tidyverse)
    library(stringr)
    df %>% 
      mutate(result=str_detect(df$string,gsub(" ", "|", df$substring)))
                     substring                 string result
    1             my new phone this is a mobile phone   TRUE
    2 She would buy new phones Yes, I have two phones   TRUE
    3            telephonessss       my old telephone  FALSE
    4             telephone234           telephone234   TRUE
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-16
      • 2011-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多