2016-02-18 23 views
2

我在R中使用survey包。我正在处理调查数据并使用svydesign()update()函数来操作数据集(创建新变量等)。未加权的svytable

这里是我如何得到加权交叉表:

## Build svytable 
Drinks_Sex <- svytable(~ Sex + Drinks, design=x) 
## Cell Totals 
round(addmargins(Drinks_Sex),0) 

##   Drinks 
## Sex   0  1 Sum 
## Female 6501 213 6714 
## Male 5254 157 5411 
## Sum 11755 370 12125 

有没有办法对我来说,使用survey包得到加权交叉表?我知道如何在原始数据集上使用基数R得到未加权的交叉表,但问题是这样做不会允许我使用update()分析任何变量。

另外:是否有任何方法可以将我使用update()完成的工作传播到原始数据集(采用csv格式),以便我可以使用基本R工作?

回答

3

updatetransform功能相同。如果您只想用transform函数替换所有update函数,并且同时用data.frame代替survey.design,那么它将起作用。

library(survey) 
data(api) 
dclus1<-svydesign(id=~dnum, weights=~pw, data=apiclus1, fpc=~fpc) 


# variables in the data.frame object inside the design are here: dclus1$variables 
# so 
head(dclus1$variables) 
# is the same as 
head(apiclus1) 

# make whatever new variable 
dclus1 <- update(dclus1 , new_col = target * 3) 
# equivalent to 
# apiclus1 <- transform(apiclus1 , new_col = target * 3) 
# so long as you are working with a data.frame object instead of a survey.design 

# just access the `variables` attribute of the survey.design object 
# as if it were a data.frame object. note: this will not work on some very complicated designs (possibly will not work on database-backed or multiply-imputed or calibrated designs) 

# single unweighted table 
table(dclus1$variables[ , 'new_col' ]) 

# crosstabs 
table(dclus1$variables[ , c('awards' , 'new_col') ]) 
+1

特别感谢您了解如何使用$变量的代码。我现在对svydesign的工作原理不再感到困惑了! 顺便说一下,我是http://www.asdfree.com的忠实粉丝。也许我错过了网站的这部分内容,但鉴于您关注的是国家数据集,诸如“使用”调查“软件包的实用介绍”这样的教程可能会非常有帮助!只是一个想法,如果你发现自己有一些空闲时间。你可以通过阅读你的示例代码来获得它的一些东西,但是更通用的东西,而不是数据集特定的,会很可爱。 –

+1

谢谢@TammyPham,欢迎您提供一个小插曲asdfree。我从'svymean'和'survey'软件包网站等地学到了我所知道的。请注意,输入'?? update'会显示'?survey ::: update.survey.design',它指出'现在有一个base-R函数变换用于向数据框添加新变量,所以我添加了变换为调查对象更新的同义词“,这是这类文档所属的地方,并回答了有关”update“同义词的问题。我认为这主要是习惯于了解在哪里看:)保持联系 –