在 R 调查函数 svychisq() 中使用动态变量规范时出错 [英] Error using dynamic variable specification in R survey function svychisq()

查看:37
本文介绍了在 R 调查函数 svychisq() 中使用动态变量规范时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 R survey 库中的函数,并根据 Stackoverflow 上的这个示例,我使用 bquote()as.name() 来动态构造指定变量的公式.

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.

这适用于 svytable(),但不适用于 svychisq().例如:

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)

terms.default(formula) 中的错误:没有terms 组件和属性

我能否让这个动态变量规范更加健壮,以便 svychisq() 选择正确的术语?

Can I make this dynamic variable-specification more robust, so that svychisq() picks up the correct terms?

推荐答案

看起来 svychisq 不像 svydesign 那样评估它的第一个参数.bquote 正在返回一个没有被计算为正确公式的语言对象.您可以自己调用 eval 来解决该问题.

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)

这篇关于在 R 调查函数 svychisq() 中使用动态变量规范时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆