2017-01-03 116 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"