I'm trying to loop through columns and print a proportion table if condition is met, or a mean table if condition is not met.
Data
library(survey)
dat <- data.frame(id=c(1,2,3), weight=c(0,2,0.1), var1=c(2,3,4), var2=c(2,6,7))
design <- svydesign(id=~1, weights=~weight, data=dat)
cols <- c("var1", "var2")
type <- c("prop", "mean")
I tried:
for(i in seq_along(cols)){
ifelse(type[i]=="prop",
print(prop.table(svytable(bquote(~.(as.name(cols[i]))), design))),
print(svymean(bquote(~.(as.name(cols[i]))), design))) }
I get this error message:
Error in array(x, c(length(x), 1L), if (!is.null(names(x))) list(names(x), :
'data' must be of a vector type, was 'language'
I am not very sure why the bquote is giving you so much problem, but if I use formula, it works ok:
for(i in seq_along(cols)){
FORMULA= as.formula(paste("~",cols[i]))
ifelse(type[i]=="prop",
print(prop.table(svytable(FORMULA, design))),
print(svymean(FORMULA, design))) }
var1
2 3 4
0.00000000 0.95238095 0.04761905
mean SE
var2 6.0476 0.0786