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 svychisq
doesn't evaluate it's first parameter in the same way that svydesign
does. The bquote
is returning a language object that's not being evaluated into a proper formula. You can call the eval yourself to overcome that issue.
svychisq(eval(bquote(~.(as.name(rowvar)) + .(as.name(colvar)) )), dstrat)
# Pearson's X^2: Rao & Scott adjustment
#
# data: svychisq(eval(bquote(~.(as.name(rowvar)) + .(as.name(colvar)))), dstrat)
# F = 77.2769, ndf = 1, ddf = 197, p-value = 7.364e-16
you could also consider building the formula as a string
svychisq(as.formula(paste("~", rowvar, "+", colvar)), dstrat)