2017-03-26 53 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