2016-03-22 51 views
0

我使用R(3.2.3)tm-package(0.6-2)並希望根據包含的部分字符串匹配來搜索我的語料庫元數據「id」。 例如,我想在「id」列中過濾包含字符串「US」的所有文檔。字符串「美國」之前和之後是各種字符和數字。R-子集通過元數據(id)匹配部分字符串的語料庫

我發現了一個類似的例子here。建議下載quanteda包,但我認爲這也應該可以用tm包。

發現另一個更相關的類似問題的答案是here。我試圖將該示例代碼適用於我的上下文。但是,我沒有設法合併部分字符串匹配。

我想我的代碼到目前爲止可能有多個錯誤。 我到目前爲止是這樣的:

US <- tm_filter(corpus, FUN = function(corpus, filter) any(meta(corpus)["id"] == filter), grep(".*US.*", corpus)) 

我收到以下錯誤信息:

Error in structure(as.character(x), names = names(x)) : 
'names' attribute [3811] must be the same length as the vector [3] 

我也不能確定如何拿出一個重複的例子,模擬我的問題了這個帖子。

回答

0

它可以像這樣工作:

library(tm) 
reut21578 <- system.file("texts", "crude", package = "tm") 
(corp <- VCorpus(DirSource(reut21578), list(reader = readReut21578XMLasPlain))) 
# <<VCorpus>> 
# Metadata: corpus specific: 0, document level (indexed): 0 
# Content: documents: 20 
(idx <- grep("0", sapply(meta(corp, "id"), paste0), value=TRUE)) 
# 502 704 708 
# "502" "704" "708" 
(corpsubset <- corp[idx]) 
# <<VCorpus>> 
# Metadata: corpus specific: 0, document level (indexed): 0 
# Content: documents: 3 

您正在尋找"US",而不是"0"。有關詳情,請參閱?grep(例如fixed=TRUE)。

+0

非常感謝!它確實存在我需要的東西。 – tarti