Reputation: 13
I am calculating confidence intervals in R from the PropCIs package. So far I am calculating these all individually, separately running the exactci function and manually extracting the upper and lower confidence intervals. This is very time consuming considering I have a large dataset.
I imagine a loop would help make this straightforward but I would appreciate advice on how to execute this.
So far, here is my code:
#Creating a dummy data frame
success<-c(5,20,30)
n<-c(300,300,300)
data<-data.frame(success, n)
#Here I have been manually entering the data to the exactci function
library(PropCIs)
exactci(5,300, conf.level=0.95)
exactci(20,300, conf.level=0.95)
exactci(30,300, conf.level=0.95)
How would I conduct this using a loop, while also adding two extra columns to my dataframe to store the output (upper and lower confidence intervals)?
Upvotes: 1
Views: 399
Reputation: 3923
Since exactci
produces an htest
object, you can also use broom
and purrr
library(purrr)
library(broom)
library(PropCIs)
map2_df(.x = data$success,
.y = data$n,
~ broom::tidy(exactci(.x,
.y,
conf.level = .95)
)) %>%
cbind(data, .)
#> success n conf.low conf.high
#> 1 5 300 0.005433205 0.03846374
#> 2 20 300 0.041194016 0.10108565
#> 3 30 300 0.068491684 0.13967331
Your data
data <- data.frame(success = c(5,20,30),
n = c(300,300,300)
)
Upvotes: 0
Reputation: 389047
You can use any of the apply*
loop :
library(PropCIs)
data[c('lower.ci', 'upper.ci')] <- t(mapply(function(x, y)
exactci(x,y, conf.level=0.95)$conf.int, data$success, data$n))
data
# success n lower.ci upper.ci
#1 5 300 0.005433 0.03846
#2 20 300 0.041194 0.10109
#3 30 300 0.068492 0.13967
Upvotes: 1