R- 通过匹配部分字符串的元数据 (id) 对语料库进行子集化

R- Subset a corpus by meta data (id) matching partial strings

我正在使用 R (3.2.3) tm-package (0.6-2) 并希望根据元数据 "id" 中包含的部分字符串匹配对我的语料库进行子集化。 例如,我想过滤所有在 "id" 列中包含字符串 "US" 的文档。字符串 "US" 的前后会有各种字符和数字。

我找到了一个类似的例子here。建议下载 quanteda 包,但我认为 tm 包也可以。

已找到与类似问题更相关的答案 。我试图使该示例代码适应我的上下文。但是,我没有设法合并部分字符串匹配。

我想到目前为止我的代码可能有很多问题。 到目前为止我所拥有的是这样的:

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] 

我也不确定如何想出一个可重现的例子来模拟我的问题 post。

它可以像这样工作:

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)。