【问题标题】:Running 'prop.test' multiple times in R在 R 中多次运行“prop.test”
【发布时间】:2025-11-24 02:15:01
【问题描述】:

我有一些数据显示一长串地区、每个地区的人口以及每个地区患有某种疾病的人数。我试图显示每个比例的置信区间(但我没有测试这些比例在统计上是否不同)。

一种方法是手动计算标准误差和置信区间,但我想使用像 prop.test 这样的内置工具,因为它有一些有用的选项。但是,当我将 prop.test 与向量一起使用时,它会对所有比例进行卡方检验。

我已经用一个while循环解决了这个问题(见下面的虚拟数据),但我觉得必须有一个更好、更简单的方法来解决这个问题。将在这里申请工作,以及如何?谢谢!

dat <- data.frame(1:5, c(10, 50, 20, 30, 35))
names(dat) <- c("X", "N")
dat$Prop <- dat$X / dat$N

ConfLower = 0
x = 1
while (x < 6) {
    a <- prop.test(dat$X[x], dat$N[x])$conf.int[1]
    ConfLower <- c(ConfLower, a)
    x <- x + 1
}

ConfUpper = 0
x = 1
while (x < 6) {
    a <- prop.test(dat$X[x], dat$N[x])$conf.int[2]
    ConfUpper <- c(ConfUpper, a)
    x <- x + 1
}

dat$ConfLower <- ConfLower[2:6]
dat$ConfUpper <- ConfUpper[2:6] 

【问题讨论】:

    标签: r while-loop apply confidence-interval


    【解决方案1】:

    这是使用Map 的尝试,基本上是从以前的答案中窃取的:
    https://*.com/a/15059327/496803

    res <- Map(prop.test,dat$X,dat$N)
    dat[c("lower","upper")] <- t(sapply(res,"[[","conf.int"))
    
    #  X  N      Prop       lower     upper
    #1 1 10 0.1000000 0.005242302 0.4588460
    #2 2 50 0.0400000 0.006958623 0.1485882
    #3 3 20 0.1500000 0.039566272 0.3886251
    #4 4 30 0.1333333 0.043597084 0.3164238
    #5 5 35 0.1428571 0.053814457 0.3104216
    

    【讨论】:

    • 这非常有效 - 谢谢。双方括号的作用是什么?
    • @Dan - [[ 是一个用于提取列表部分内容的函数 - 请参阅 ?Extractsapply 行本质上是通过列表res 的循环,从运行prop.test 的每个结果中获取每个conf.int 组件。这相当于先做"[["(res[[1]],"conf.int") 然后"[["(res[[2]],"conf.int") 等等...