我对那些希望推广到更大人群的样本进行大量工作。但是,大多数时候样本都有偏差,需要用survey包进行加权。但是,我还没有找到一种方法来对这些权重的术语文档矩阵加权。考虑这个例子在TermDocumentMatrix中使用调查软件包中的权重
library(tm)
library(wordcloud)
set.seed(123)
# Consider this example: I have performed a sample from a population and now have
# 1000 observations of text. In the data I also have information about gender.
# The sample
data <- rbind(data.frame(gender = "M",
words = sample(c("education", "money", "family",
"house", "debts"),
600, replace = TRUE)),
data.frame(gender = "F",
words = sample(c("career", "bank", "friends",
"drinks", "relax"),
400, replace = TRUE)))
# I create a simple wordcloud
text <- paste(data$words, collapse = " ")
matrix <- as.matrix(
TermDocumentMatrix(
VCorpus(
VectorSource(text)
)
)
)
正如你所看到的,男性中提到的术语是更大的,因为出现更频繁。但是,我知道这个人口的真实分布,因此这个wordcloud是有偏见的。
真正性别分布
true_gender_dist <- data.frame(gender = c("M", "F"), freq = nrow(data) * c(0.49,0.51))
随着调查包我可以用耙功能
library(survey)
rake_data <- rake(design = svydesign(ids = ~1, data = data),
sample.margins = list(~gender),
population.margins = list(true_gender_dist))
为了使用权重分析中,可视化等加权数据(即是未包含在调查包中)我将权重添加到原始数据。
data_weighted <- cbind(data, data.frame(weights = weights(rake_data)))
到目前为止好。不过,我想写一个将这些权重考虑在内的wordcloud。
我的第一次尝试是在制作术语文档矩阵时使用权重。
text_corp <- VCorpus(VectorSource(text))
w_tdm <- TermDocumentMatrix(text_corp,
control = list(weighting = weights(rake_data)))
但后来我得到:
Error in .TermDocumentMatrix(m, weighting) : invalid weighting
在示例中,您不需要'样本'作为'性别'列。 'data.frame(gender = 1,...'will do –
您可以使用[inverse document frequency(idf)](https://en.wikipedia.org/wiki/Tf%E2%80%93idf)来加权术语频率。或者只是按照每个性别的调查数量来划分每个性别的词频。 – emilliman5
是的,@ emilliman5,这是我想到的那种东西。只是不知道我会如何编程。猜猜我将不得不尝试使用TM包,它具有指定权重的功能。由于权重也可能将事情视为政治偏见,年龄等,我正在寻找更复杂的方式。 – FilipW