0

I want to change the variable (which represents a dataframe column), that is a part of the formula, for looping this formula. It's important that I want to insert one var at the moment, because I want to work with this variable later, and only then to change it to another one (so, I guess "lapply" with a list of variables wouldn't be a solution?)

svychisq(~var1 + strata, svy_design)

I need this var1 (name of column) to be changed in a loop / function

1 Answers1

1

Get all the variables in a vector and create a formula object using sprintf/paste0.

library(survey)

cols <- c('var1', 'var2')
#If you want all the variables that have 'var' in it. 
#cols <- grep('var', names(df), value = TRUE)
result <- lapply(cols, function(x) {
  svychisq(as.formula(sprintf('~%s + strata', x)), svy_design)
})
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213