Error using dynamic variable specification in R survey function svychisq()

混江龙づ霸主 提交于 2020-01-06 14:44:10

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/26918065/error-using-dynamic-variable-specification-in-r-survey-function-svychisq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!