1

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

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

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

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

任何帮助将不胜感激。

更新:我真正想做的是避免指定变量名称,而是给出变量组合的向量。例如

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

1 回答 1

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]]
于 2012-11-15T21:30:08.983 回答