2016-11-28 23 views
0

我对那些希望推广到更大人群的样本进行大量工作。但是,大多数时候样本都有偏差,需要用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,看起来是这样的: enter image description here

正如你所看到的,男性中提到的术语是更大的,因为出现更频繁。但是,我知道这个人口的真实分布,因此这个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 

这是在所有可能的?

+0

在示例中,您不需要'样本'作为'性别'列。 'data.frame(gender = 1,...'will do –

+0

您可以使用[inverse document frequency(idf)](https://en.wikipedia.org/wiki/Tf%E2%80%93idf)来加权术语频率。或者只是按照每个性别的调查数量来划分每个性别的词频。 – emilliman5

+0

是的,@ emilliman5,这是我想到的那种东西。只是不知道我会如何编程。猜猜我将不得不尝试使用TM包,它具有指定权重的功能。由于权重也可能将事情视为政治偏见,年龄等,我正在寻找更复杂的方式。 – FilipW

回答

0

我不能评论,所以我将使用的答案评论你的问题:

你可能有兴趣在R包STM(结构化的主题模型)。它提供了推断关于元变量(连续和/或离散)的潜在主题的可能性。

可以产生不同类型的地块退房元变量如何影响

一)根据所选择的主题,

B)一个主题内的首选话,

c)和一些:)

一些链接,如果你有兴趣:

Paper describing the R package

R documentation

Some more Papers < - 这是一个很好的集合,如果你想潜入受一些!

+0

感谢您的提示。有趣的包。但是,如果我没有记错,TM-package也提供了存储元变量的能力,但是,stm-modeling是有趣的。不过,并不是我正在寻找的东西。按照最基本的形式,我有兴趣根据元变量给出每个词的频率权重。 – FilipW

相关问题