Search code examples
rsurvey

Loop though columns and print tables using survey weights from survey package


I am trying to loop though columns of a dataset and create proportion tables. The survey package requires a '~' before variables making it tricky to loop through columns.

Data and design:

library(survey)
dat <- data.frame(id=c(1,2,3), weight=c(0,2,0.1), var1=c(2,3,5), var2=c(2,6,7))
design <- svydesign(id=~1, weights=~weight, data=dat)

Attempt:

cols <- c("var1", "var2") # columns to loop through
for(i in seq_along(cols)) {
prop.table(svytable(~i, design))
}

I get the following error message:

Error in model.frame.default(formula = weights ~ i, data = model.frame(design)) : variable lengths differ (found for 'i')

Thank you


Solution

  • Acknowledging the use of bquote as a partial substitution in expression from Ben's comment above, you could modify your for loop as follows:

    cols <- c("var1", "var2") # columns to loop through
    for(i in  seq_along(cols)){
      print(prop.table(svytable(bquote(~.(as.name(cols[i]))), design)))
    } 
    # var1
    #          2          3          5 
    # 0.00000000 0.95238095 0.04761905 
    # var2
    #          2          6          7 
    # 0.00000000 0.95238095 0.04761905 
    

    Data

    library(survey)
    dat <- data.frame(id=c(1,2,3), weight=c(0,2,0.1), var1=c(2,3,5), var2=c(2,6,7))
    design <- svydesign(id=~1, weights=~weight, data=dat)