2017-03-26 59 views
2

我有以下的数据帧:精确匹配于单词列表字对于每一列

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 

我发现匹配函数可以为一个字符串向量中的单词做到这一点。但是,直接申请比赛时

ifelse(match(d$word, strsplit(d$sentence, ' '), nomatch=0) == 0, 0, 1) 

它不按预期工作。我认为它不是按行执行匹配操作,因为我愿意。我也研究过grep,但是我一直无法找到一种方法来让这两个函数做我想做的事情。

有什么建议吗?

谢谢!

回答

3

我们可以使用stringrstr_detect来检查'word'是否在'句子'中。为了防止串匹配,我们可以在“词”的开始和结束

library(stringr) 
d$isInSentence <- as.integer(str_detect(d$sentence, paste0("\\b", d$word, "\\b"))) 
d$isInSentence 
#[1] 1 0 0 

在OP的码字paste边界(\\b),该strsplit返回list。因此,我们需要通过相应的list元素与“单词”进行循环。为此,可以使用Map/mapply。对于没有匹配,默认情况下我们得到NA。因此,它可以被转换为logicalis.na然后强制为整数与as.integer

as.integer(!is.na(mapply(match, d$word, strsplit(d$sentence, ' ')))) 
#[1] 1 0 0