具有误差幅度的因子

时间:2016-12-09 22:56:58

标签: r

我创建了一个分组比例表。在指定的置信区间内包含误差范围的最简单方法是什么?

data.frame(prop.table(table(df$variable, df$group),2))

SummarySE()应该有效,但我的变量是一个有三个级别的因子,而不是一个数值。

1 个答案:

答案 0 :(得分:0)

你真的应该用置信区间来指定你的意思,但是假设你想要比例的二项式置信区间,这不一定很漂亮但是它有效。以此为出发点,适应您的需求:

ci.table <- function(tbl, margin = NULL) {
    binom_ci <- function(x, n) {
        paste(round(binom.test(x, n)$conf.int, 3), collapse = " - ")
    }
    sweep_ci <- function(xx, nn) { mapply(FUN = binom_ci, xx, nn) }

    if (length(margin))
        result <- sweep(tbl, margin, margin.table(tt, margin),
                        "sweep_ci", check.margin = FALSE)       
    else
        result <- sweep_ci(tbl, sum(tbl))

    dim(result) <- dim(tbl)
    as.table(result)
}

binom_ci函数处理格式。对于置信区间我并不特别喜欢“x - y”,但我发现大多数人比“(x,y)”更好地理解这个......

MWE:

ddff <- data.frame(
    A = sample(c("A", "B", "C"), 20, replace = TRUE),
    B = sample(c("C", "D"), 20, replace = TRUE) 
)
tt <- table(ddff$A, ddff$B)
ci.table(tt)
ci.table(tt, 1)
ci.table(tt, 2)
相关问题