结合lapply,svyby,svyratio来计算许多比率和置信区间

时间:2014-04-01 20:37:38

标签: r survey lapply

我正在使用R中的survey包来处理美国人口普查的PUMS人口数据集。我为每个广泛的行业创建了一个布尔值,并为一个字符变量MigrationStatus创建了三个值(StayedLeftEntered)。我想通过迁移状态来检查每个行业的工人比例。

这很好用:

AGR_ratio=svyby(~JobAGR, by=~MigrationStatus, denominator=~EmployedAtWork, design=subset(pums_design,EmployedAtWork==1), svyratio, vartype='ci')

但这会产生错误:

varlist=names(pums_design$variables)[32:50]
job_ratios = lapply(varlist, function(x) {
  svyby(substitute(~i, list(i = as.name(x))), by=~MigrationStatus, denominator=~EmployedAtWork, design=subset(pums_design,EmployedAtWork==1), svyratio, vartype='ci')
})

#Error in svyby.default(substitute(~i, list(i = as.name(x))), by = ~MigrationStatus,  : 
#object 'byfactor' not found

varlist

#[1] "JobADM" "JobAGR" "JobCON" "JobEDU" "JobENT" "JobEXT" "JobFIN" "JobINF" "JobMED" "JobMFG" "JobMIL" "JobPRF" "JobRET" "JobSCA" "JobSRV"
#[16] "JobTRN" "JobUNE" "JobUTL" "JobWHL"

1 个答案:

答案 0 :(得分:4)

怎么样?

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

# single example
svyby(~api99, by = ~stype, denominator = ~api00 , dclus1, svyratio)

# multiple example
variables <- c( "api99" , "pcttest" )

# breaks
lapply(variables, function(x) svyby(substitute(~i, list(i = as.name(x))), by=~stype, denominator=~api00, design=dclus1, svyratio, vartype='ci'))

# works
lapply( variables , function( z ) svyby( as.formula( paste0( "~" , z ) ) , by = ~stype, denominator = ~api00 , dclus1, svyratio , vartype = 'ci' ) )

顺便说一句,您可能对this uspums data automation syntax

感兴趣