首先,这是一个示例 data.frame
dd<-data.frame(
id=10:13,
text=c("No wonder, then, that ever gathering volume from the mere transit ",
"So that in many cases such a panic did he finally strike, that few ",
"But there were still other and more vital practical influences at work",
"Not even at the present day has the original prestige of the Sperm Whale")
,stringsAsFactors=F
)
现在,为了从 data.frame 中读取特殊属性,我们将使用 readTabular 函数来制作我们自己的自定义 data.frame 阅读器。这就是我们需要做的所有事情
library(tm)
myReader <- readTabular(mapping=list(content="text", id="id"))
我们只是指定用于内容的列和 data.frame 中的 id。现在我们使用DataframeSource 读取它,但使用我们的自定义读取器。
tm <- VCorpus(DataframeSource(dd), readerControl=list(reader=myReader))
现在,如果我们只想保留一组单词,我们可以创建自己的content_transformer 函数。一种方法是
keepOnlyWords<-content_transformer(function(x,words) {
regmatches(x,
gregexpr(paste0("\\b(", paste(words,collapse="|"),"\\b)"), x)
, invert=T)<-" "
x
})
这会将不在单词列表中的所有内容替换为空格。请注意,您可能希望在此之后运行 stripWhitespace。因此我们的转换看起来像
keep<-c("wonder","then","that","the")
tm<-tm_map(tm, content_transformer(tolower))
tm<-tm_map(tm, keepOnlyWords, keep)
tm<-tm_map(tm, stripWhitespace)
然后我们可以把它变成一个文档术语矩阵
dtm<-DocumentTermMatrix(tm)
inspect(dtm)
# <<DocumentTermMatrix (documents: 4, terms: 4)>>
# Non-/sparse entries: 7/9
# Sparsity : 56%
# Maximal term length: 6
# Weighting : term frequency (tf)
# Terms
# Docs that the then wonder
# 10 1 1 1 1
# 11 2 0 0 0
# 12 0 1 0 0
# 13 0 3 0 0
它有我们的单词列表和来自 data.frame 的正确文档 ID