【问题标题】:Looping through columns and printing proportion or mean table based on condition with survey package使用调查包循环遍历列并根据条件打印比例或均值表
【发布时间】:2019-11-16 00:52:48
【问题描述】:

我正在尝试遍历列并在满足条件时打印比例表,如果不满足条件则打印平均表。

数据

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")

我试过了:

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))) }

我收到此错误消息:

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'

【问题讨论】:

  • 不必要地将包的名称大写可能会使新手感到困惑。我会避免这种做法。

标签: r survey


【解决方案1】:

我不太确定为什么 bquote 会给您带来这么多问题,但如果我使用公式,它可以正常工作:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-17
    • 2015-10-03
    • 1970-01-01
    • 2020-10-24
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    相关资源
    最近更新 更多