繁体   English   中英

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”之前和之后是各种字符和数字。

在这里找到了类似的例子。 建议下载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] 

我也不确定如何提出一个可重现的示例来模拟本文的问题。

它可以像这样工作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM