2017-01-03 112 views
2

我有一組語句搜索從關鍵詞和發生的標籤關鍵字的列表

statement <- as.matrix(c("the cat sat on the mat", 
          "the dog ran up the hill", 
          "the dog ran up the hill to the mat")) 

和關鍵字

keywords <- as.matrix(c("cat", "mat", "dog", "hill"))

我想中的搜索列表來自我的關鍵字列表並標記出現了什麼關鍵字,即有結果

statement        keywords 
the cat sat on the mat    cat, mat 
the dog ran up the hill    dog, hill 
the dog ran up the hill to the mat dog, hill, mat 

我想一個辦法,我能做到這一點是使用grep在某種程度上像

statement[grep("cat", statement$V1, ignore.case = TRUE), "keywords"] <- "cat" 
statement[grep("mat", statement$V1, ignore.case = TRUE), "keywords"] <- "mat" 

...等,但首先,這將不會給標籤對我來說發生的所有關鍵字。其次,如果我想找到這樣的方式,當我有一個大名單可以說,1000個關鍵詞和語句500將只是笨拙。

你怎麼會建議一個樣?有沒有使用grep的方法,或者是否有任何可以從預定列表中挖掘文本並返回關鍵字的包?

謝謝!

+0

是否有必要對這些是矩陣對象?或者矢量是否足夠? – Benjamin

+0

@benjamin載體會在這種情況下是足夠 –

+0

@DarshanBaral的感謝!這是真正有用的 –

回答

0
keywords <- c("cat", "mat", "dog", "hill") 
m = sapply(keywords, grepl, statement) 
     cat mat dog hill 
[1,] TRUE TRUE FALSE FALSE 
[2,] FALSE FALSE TRUE TRUE 
[3,] FALSE TRUE TRUE TRUE 

apply(m,1, function(y) paste0(colnames(m)[y], collapse=",")) 
[1] "cat,mat"  "dog,hill"  "mat,dog,hill" 

或者在單個行:由「」分裂的statement每一行,然後檢查使用%in%哪些詞存在和paste它們全部

apply(statement, 1, function(i) paste0(x[x %in% unlist(strsplit(i, " "))], collapse=",")) 
[1] "cat,mat"  "dog,hill"  "mat,dog,hill" 
+0

訪問此http://stackoverflow.com/help/someone-answers並接受一個爲你喜歡的準確的答案 –

1

可以使用stringi包,

library(stringi) 
sapply(stri_extract_all_regex(statement[,1], 
         paste(keywords[,1], collapse = '|')), toString) 

#[1] "cat, mat"  "dog, hill"  "dog, hill, mat"