I'm using the survey function to compute the chi-square test in R. I have a list of variables I would like to apply the function. This is my code.
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
}
I get an error. I think the function is not reading the variable from the list, is there another way to call the variables? Thanks in advance.
Alternatively, you can use substitute
or bquote
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)
}
The slight advantage of this is the the variable name ends up in the formula (rather than dict[i]
), so your output is
Pearson's X^2: Rao & Scott adjustment
data: svychisq(~x + z, dclus1, statistic = "Chisq")
X-squared = 5.0086, df = 2, p-value = 0.08268
rather than
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
is the base R version of the unquote and unquote-and-splice that the tidyverse uses !!
and !!!
for.