【问题标题】:R Looping through in survey packageR在调查包中循环
【发布时间】:2012-11-04 08:47:16
【问题描述】:

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

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

我注意到有人做过类似here 的事情,但大部分变量都是固定的。任何人都可以创建一个函数(可能类似于this 答案)但使用 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 = '+')) 

【问题讨论】:

    标签: r survey


    【解决方案1】:
    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]]
    

    【讨论】:

    • 谢谢!就一件事。我的目标是将所有唯一变量组合放在一个向量中(否则列出这些对就像使用原始函数一样)。让我们举一个只有三个独特组合的例子:变量 2,16 和 17。当我尝试像这样自动创建 cols.to.chisq 时: cols.to.chisq
    • #我已经编辑了我的答案..我认为这就是你需要的?但是当我运行你的代码时.. cols.to.chisq
    • 可能是我的错误。再次感谢
    • 我喜欢上面的答案,它对包含 2000 多个变量的数据集帮助很大。我能问一下有没有办法合并子集数据集。如果我想在我的所有变量中运行上述函数测试男性受访者与女性受访者?
    • @DataDancer 可能是 ?svyby ... 否则请使用 [r] 和 [survey] 标签提出单独的 stackoverflow 问题,谢谢
    猜你喜欢
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2019-09-05
    • 1970-01-01
    • 2022-01-14
    • 2019-10-21
    相关资源
    最近更新 更多