I am using the functions in the R survey-library, and per this example on Stackoverflow, I use bquote() and as.name() to dynamically construct the formula for specifying the variables.
This works fine for svytable(), but not for svychisq(). For example:
library(survey)
data(api)
dstrat<-svydesign(id=~1,strata=~stype, weights=~pw, data=apistrat, fpc=~fpc)
colvar <- 'sch.wide'
rowvar <- 'awards'
svytable(bquote(~.(as.name(rowvar)) + .(as.name(colvar)) ), dstrat)
sch.wide
awards No Yes
No 1065.69 1170.74
Yes 0.00 3957.57
svychisq(bquote(~.(as.name(rowvar)) + .(as.name(colvar)) ), dstrat)
Error in terms.default(formula) : no terms component nor attribute
Can I make this dynamic variable-specification more robust, so that svychisq() picks up the correct terms?
It looks like
svychisqdoesn't evaluate it's first parameter in the same way thatsvydesigndoes. Thebquoteis returning a language object that's not being evaluated into a proper formula. You can call the eval yourself to overcome that issue.you could also consider building the formula as a string