R 每列单词列表中单词的精确匹配
我有以下数据框:R 每列单词列表中单词的精确匹配,r,R,我有以下数据框: word sentence cat the cat was red blue the cat was red dog the dogs 我想添加一个0或1的新列,这取决于单词在句子中是否完全匹配,即 word sentence isInSentence cat the cat was red 1 blue the cat was red 0 dog the dogs
word sentence
cat the cat was red
blue the cat was red
dog the dogs
我想添加一个0或1的新列,这取决于单词在句子中是否完全匹配,即
word sentence isInSentence
cat the cat was red 1
blue the cat was red 0
dog the dogs 0
我发现match函数可以对字符串向量中的一个单词进行匹配。但是,当我直接应用match时
ifelse(match(d$word, strsplit(d$sentence, ' '), nomatch=0) == 0, 0, 1)
它没有按预期工作。我认为它没有像我希望的那样按行执行匹配操作。我也研究过grep,但是我还没有找到一种方法让这两个函数都能实现我想要的功能
有什么建议吗
谢谢 我们可以使用
stru detect
fromstringr
检查“单词”是否在“句子”中。为了防止子字符串匹配,我们可以在“word”的开头和结尾粘贴单词边界(\\b
)
library(stringr)
d$isInSentence <- as.integer(str_detect(d$sentence, paste0("\\b", d$word, "\\b")))
d$isInSentence
#[1] 1 0 0
as.integer(!is.na(mapply(match, d$word, strsplit(d$sentence, ' '))))
#[1] 1 0 0