我有三个矢量。一个包含文本或实际单词/句子(文本),一个向量包含我要搜索的单词(xreg),第三个向量(类别)包含每个文本如果找到匹配应该属于的类别。以下是三个向量:
text <- c("Sole Service here", "Freedom to Include","Freedom to Incl","Premier Reg",
"Bankhall","Bankhall","Premier Regiona","St James Play",
"Premier Regional","Health online","Premier Regional",
"Tenet","Health on line","Tenet","Nations","Woolwich",
"Premier Regional","Lifesearch","Nations","Bankhall",
"Premier Regional","Sole Service her","Lifesearch",
"Premier Regional","Sole Service","Nations",
"Sole Service","First Money service","Sole Service",
"Nations wide","Sole Service","Premier Region")
text <- tolower(text)
xreg <- c("sole","freedom","premier","bankhall","james","health","tennet",
"nations","woolwich","life","money")
categories <- c("SS", "FD", "PR", "BK", "JM", "HT", "TT", "NT", "WW", "LF", "MY")我想根据‘xreg’向量中的搜索词搜索‘文本’向量。然后,在找到匹配项后,我想将这些单词放入“类别”向量中提到的类别中。
比如,查找单词‘state’,在有匹配的地方,记下该单词的索引,或者简单地用单词创建一个数据框架,然后单独一个列来说明它应该属于的类别。在“独家”的情况下,把它放在“SS”类别中。“自由”把它归为“FD”类等等。
到目前为止,解决方案:,我可以逐个搜索每个关键字,它会告诉我它在哪里找到匹配的索引。
reg_func <- function(x){grep(x,text)
}
reg_func("sole")
reg_func("freedom")这将为每个匹配的单词提供索引,然后我可以使用这些索引来更新类别。有什么办法能让我做得更快吗?而不是一次只搜索一个词?谢谢
发布于 2018-11-12 15:46:25
解释@Andre Elrico答案中使用的函数
apply(
sapply(xreg, function(x) {grepl(x, text, ignore.case = T)}), 1, function(x) xreg[x]
)
# Apply each xreg pattern to the text vector and see if there's a match
# result is TRUE or FALSE gives each index where there is a match
sapply(xreg, function(x) {grepl(x, text, ignore.case = T)})结果
sole freedom premier bankhall james health tennet nations woolwich life money
[1,] TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[2,] FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[3,] FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[4,] FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[5,] FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[6,] FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
# Now apply each xreg element to the TRUE's from the previous result
# and see which element of xreg it matches with
apply(
sapply(xreg, function(x) {grepl(x, text, ignore.case = T)}), 1, function(x) xreg[x]
)结果
[[1]]
[1] "sole" "premier"
[[2]]
[1] "freedom"
[[3]]
[1] "freedom"
[[4]]
[1] "premier"
[[5]]
[1] "bankhall"
[[6]]
[1] "bankhall"现在,获取每个匹配项的类别(Regex)
sapply(ans$xreg_m, function(x) unique(unname( categories[x] )))上面写着:
# Take each element of xreg_m (our matched terms) and
# see which element in the categories vector it matches with
# Then unname the result so you only get the categoryhttps://stackoverflow.com/questions/53189208
复制相似问题