r-使用调查函数从列表中调用变量的问题



我正在使用survey函数来计算R中的卡方检验。我有一个变量列表,我想应用该函数。这是我的密码。

library("survey")
#fake data 
dataset<-data.frame(id=seq(1,1000,1), expFact=round(rnorm(1000,70,4)), x=sample(c(1,2,3),1000, replace = T), 
y = sample(c(1,2,3,4),1000, replace = T), 
z=sample(c(1,2),1000, replace = T) )

dict<-c("x", "y")
for (i in 1:2){
dclus1<-svydesign(ids=~id, weights=~expFact, strata=NULL, data = dataset)
chi_quadrad<-svychisq(~ get(dict[i])  + z , dclus1, statistic="Chisq")
chi_quadrad
}

我犯了一个错误。我认为函数没有从列表中读取变量,有其他方法可以调用变量吗?提前谢谢。

或者,您可以使用substitutebquote

dclus1<-svydesign(ids=~id, weights=~expFact, strata=NULL, data = dataset)
for(i in 1:2){
chi_quadrad <- eval(bquote(svychisq(~.(as.name(dict[i]))+z, dclus1, statistic="Chisq")))
print(chi_quadrad)
}

这样做的一个小优点是变量名最终出现在公式中(而不是dict[i](,因此您的输出是

Pearson's X^2: Rao & Scott adjustment
data:  svychisq(~x + z, dclus1, statistic = "Chisq")
X-squared = 5.0086, df = 2, p-value = 0.08268

而不是

Pearson's X^2: Rao & Scott adjustment
data:  svychisq(as.formula(paste0("~", dict[i], "+z")), dclus1, statistic = "Chisq")
X-squared = 5.0086, df = 2, p-value = 0.08268

bquote是tidyverse使用!!!!!的unquote和unquote and splice的基本R版本。

您可以使用as.formula从字符串构造公式

for (i in 1:2) {
dclus1<-svydesign(ids=~id, weights=~expFact, strata=NULL, data = dataset)
chi_quadrad <- svychisq(as.formula(paste0("~", dict[i], "+z")), dclus1, statistic="Chisq")
chi_quadrad
}

最新更新