如何找到一列中的一个/多个单词出现在组成一个句子的另一列中 [英] How to find that a word/words in a column is present in another column consisting a sentence

查看:23
本文介绍了如何找到一列中的一个/多个单词出现在组成一个句子的另一列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking forward to an R solution that can check whether a word or a sentence (in column 1) is present in the sentence (in column 2) of a data frame or not. If the word/words are present in the sentence, then it should return 1 (TRUE) or else 0 (FALSE). and

推荐答案

这应该适合你:

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.

You could get more fancy with creating the lookup column, but for this case there is no need so I used a simple 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"))

这篇关于如何找到一列中的一个/多个单词出现在组成一个句子的另一列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆