R在调查包中循环

时间:2012-11-15 17:19:55

标签: r survey

我在使用调查包循环变量时遇到问题。假设我将一组变量与调查权重一起收集到数据框中,我想进行卡方检验。考虑到多次测试的问题,我仍然想测试所有独特的组合。这在R中通常相对简单,并且有一个很好的例子here

不幸的是,这在调查包中变得更难,因为项目需要在设计对象中,最重要的是不支持数据集索引(至少据我所知)。我已经尝试将上面提到的例子改编成svychisq,但我的所有策略都失败了。

我注意到有人做了类似here的事情,但大多数变量都是固定的。有人能够创建一个函数(可能类似于this回答),但使用svychisq函数?不幸的是,我不知道有很多分类变量和在线可用的复杂设计的数据集。出于演示的目的,我假设可以在数据(api)中使用dclus1,如函数帮助文件中所示,并尝试遍历前10个变量

library(survey)
data(api)
dclus1<-svydesign(id=~dnum, weights=~pw, data=apiclus1, fpc=~fpc)
svychisq(~sch.wide+stype, dclus1)

非常感谢任何帮助。

更新:我真正想要做的是避免指定变量名称并改为给出变量组合的向量。 e.g。

MyChi2tests <- apply( combn(colnames(apiclus1[,c(2,16:17)]),2), 2, function(z) paste(z, collapse = '+')) 

1 个答案:

答案 0 :(得分:4)

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

# run a simple example svychisq() function
svychisq( ~sch.wide+stype , dclus1 )

# create a function that requires a character string (containing the variables)
# and the design object and runs the svychisq() 
# on the contents of that character string's columns
scsloop <- function( vars , design ){ svychisq( as.formula( paste0( "~" , vars ) ) , design ) }

# test it out
scsloop( "sch.wide+stype" , dclus1 )
scsloop( "sch.wide+comp.imp" , dclus1 )

# either create a character vector to run it multiple times
cols.to.chisq <- c( "sch.wide" , "comp.imp" , "stype" )

# or identify them based on column number, if you prefer
cols.to.chisq <- names( apiclus1 )[ c( 2 , 16 , 17 ) ]


# find every combination of that vector, taken two at a time
combos <- combn( cols.to.chisq , 2 )

# separate them by +
col.combos <- paste( combos[ 1 , ] , combos[ 2 , ] , sep = "+" )

# run it on each of those character strings (print to screen and save to list)
( x <- lapply( col.combos , scsloop , dclus1 ) )

# just for kicks, print everything to the screen
col.combos[1] ; x[[1]]
col.combos[2] ; x[[2]]
col.combos[3] ; x[[3]]