Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 每列单词列表中单词的精确匹配_R - Fatal编程技术网

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
from
stringr
检查“单词”是否在“句子”中。为了防止子字符串匹配,我们可以在“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