2012-11-15 154 views
1

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

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

我注意到有人做了类似​​的东西,但大部分变量都是固定的。任何人都可以创建一个函数(类似this的答案也许),但使用svychisq函数?不幸的是,我不知道有大量分类变量和复杂的在线设计数据集。出于演示的目的,我想一个能够在数据(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
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]] 
+0

谢谢!就一件事。我的目标是将所有独特的变量组合放入一个向量中(否则列出这些对就好像用原始函数一样)。让我们举一个只有三个独特组合的例子:变量2,16和17.当我尝试像这样自动创建cols.to.chisq时:cols.to.chisq < - apply(combn(colnames(apiclus1 [,c(2 ,16:17)]),2),2,function(z)paste(z,collapse ='+')) 然后像上面那样在lapply中运行它我得到一个错误。 as.integer(.margins)中的错误: 无法强制将类型'closure'转换为'integer'类型的向量 – maycobra

+0

#我编辑了我的答案..我认为这就是您需要的吗?但是当我运行你的代码时。 cols.to.chisq < - apply(combn(colnames(apiclus1 [,c(2,16:17)]),2),2,function(z)paste(z,崩溃= '+')) #,然后lapply使用我scsloop功能 lapply(cols.to.chisq,scsloop,dclus1) #它工作正常,我.. :) –

+0

也许我的错误。再次感谢 – maycobra