I\'m having problems looping through variables using the survey package. Let\'s say I have a subset of variables I collect into a dataframe together with the survey weight a
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]]