简体   繁体   中英

Running 'prop.test' multiple times in R

I have some data showing a long list of regions, the population of each region and the number of people in each region with a certain disease. I'm trying to show the confidence intervals for each proportion (but I'm not testing whether the proportions are statistically different).

One approach is to manually calculate the standard errors and confidence intervals but I'd like to use a built-in tool like prop.test, because it has some useful options. However, when I use prop.test with vectors, it runs a chi-square test across all the proportions.

I've solved this with a while loop (see dummy data below), but I sense there must be a better and simpler way to approach this problem. Would apply work here, and how? Thanks!

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] 

Here's an attempt using Map , essentially stolen from a previous answer here:
https://stackoverflow.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM