r - STM : how to keep metadata when converting from tm to stm document-term matrix?

标签 r matrix tm topic-modeling text-analysis

我正在尝试在使用 tm 包准备的文档术语矩阵上运行结构主题模型(使用 stm 包)。

我在 tm 包中构建了一个语料库,其中包含以下元数据:

library(tm)

myReader2 <- readTabular(mapping=list(content="text", id="id", sentiment = "sentiment"))
text_corpus2 <- VCorpus(DataframeSource(bin_stm_df), readerControl = list(reader = myReader2))

meta(text_corpus2[[1]])
  id       : 11
  sentiment: negative
  language : en

在进行一些文本清理并将结果保存为 clean_corpus2(元数据仍然存在)之后,我将其更改为文档术语矩阵,然后将其读取为 stm-兼容矩阵:

library(stm)

chat_DTM2 <- DocumentTermMatrix(clean_corpus2, control = list(wordLengths = c(3, Inf)))
DTM2 <- removeSparseTerms(chat_DTM2 , 0.990)
DTM_st <-readCorpus(DTM2, type = "slam")

到目前为止,一切都很好。但是,当我尝试使用 stm 兼容数据指定元数据时,元数据消失了:

docsTM <- DTM_st$documents # works fine
vocabTM <- DTM_st$vocab # works fine
metaTM <- DTM_st$meta # returns NULL

> metaTM
NULL

如何将 tm 生成的语料库中的元数据保留在 stm 兼容的文档术语矩阵中?欢迎任何建议,谢谢。

最佳答案

尝试quanteda软件包怎么样?

如果无法访问您的对象,我无法保证它逐字有效,但它应该:

library("quanteda")

# creates the corpus with document variables except for the "text"
text_corpus3 <- corpus(bin_stm_df, text_field = "text")

# convert to document-feature matrix - cleaning options can be added
# see ?tokens
chat_DTM3 <- dfm(text_corpus3)

# similar to tm::removeSparseTerms()
DTM3 <- dfm_trim(chat_DTM3, sparsity = 0.990)

# convert to STM format
DTM_st <- convert(DTM3, to = "stm")

# then it's all there
docsTM <- DTM_st$documents 
vocabTM <- DTM_st$vocab    
metaTM <- DTM_st$meta      # should return the data.frame of document variables

关于r - STM : how to keep metadata when converting from tm to stm document-term matrix?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47652890/

相关文章:

r - 合并两个不同大小的数据集,有条件地将同一行从较小的数据集复制到较大数据集中的几行

r - .subset2(x, i, exact = exact) 错误 : subscript out of bounds in R

python - 对矩阵列进行排序

arrays - Julia 使用向量作为索引访问特定的 Matrix 元素

R tm 包 : utf-8 text

r - 可用的CRAN渐晕

regex - R- 文本值连续显示多少次?

c++ - boost库中的矩阵赋值如何与括号一起使用?

c++ - 结构tm时间; vs tm 时间 = {}。输出相同但不一样?

html - 为什么 extractHTMLStrip() from tm.plugin.webmining 会截断 61 个字符以下的字符串?