我试图遍历数据集的列并创建比例表。问卷调查包在变量之前需要加一个〜,以使其难以遍历各列。
数据和设计:
library(survey)
dat <- data.frame(id=c(1,2,3), weight=c(0,2,0.1), var1=c(2,3,5), var2=c(2,6,7))
design <- svydesign(id=~1, weights=~weight, data=dat)
尝试:
cols <- c("var1", "var2") # columns to loop through
for(i in seq_along(cols)) {
prop.table(svytable(~i, design))
}
我收到以下错误消息:
Error in model.frame.default(formula = weights ~ i, data = model.frame(design)) :
variable lengths differ (found for 'i')
谢谢
答案 0 :(得分:1)
从上文Ben的注释中确认使用bquote
作为表达式的部分替换,您可以按以下方式修改for loop
:
cols <- c("var1", "var2") # columns to loop through
for(i in seq_along(cols)){
print(prop.table(svytable(bquote(~.(as.name(cols[i]))), design)))
}
# var1
# 2 3 5
# 0.00000000 0.95238095 0.04761905
# var2
# 2 6 7
# 0.00000000 0.95238095 0.04761905
library(survey)
dat <- data.frame(id=c(1,2,3), weight=c(0,2,0.1), var1=c(2,3,5), var2=c(2,6,7))
design <- svydesign(id=~1, weights=~weight, data=dat)