Reputation: 13969
I would like to bootstrap confidence intervals for a proportion from a data.frame
. I would like to get the results for the variables in one of my columns.
I have managed to perform the bootstrap for a vector but do not know how to scale it up to a data.frame
from here.
A simplified example setting a threshold value of 10 and looking at the proportion less than 10 in the data.
Vector solution:
library(boot)
vec <- abs(rnorm(1000)*10) #generate example vector
data_to_tb <- vec
tb <- function(data) {
sum(data < 10, na.rm = FALSE)/length(data) #function for generating the proportion
}
tb(data_to_tb)
boot.out <- boot(data = data_to_tb, function(u,i) tb(u[i]), R = 999)
quantile(boot.out$t, c(.025,.975))
And from here I would like to do the same for a data.frame
containing two columns.
I would like to return the result in a "summarized" data.frame
if possible, with columns (x, sample, proportion, CI) :
x n proportion CI
A xx xx xx
B xx xx xx
C xx xx xx
Would be extra good if dplyr
package could be used.
Here is a simplified example of my data:
Example:
dataframe <- data.frame(x = sample(c("A","B","C"),100,replace = TRUE), vec =abs(rnorm(100)*10))
head(dataframe)
## x vec
## 1 B 0.06735163
## 2 C 0.48612358
## 3 B 2.34190635
## 4 C 0.36393262
## 5 A 7.99762969
## 6 B 1.43293330
Upvotes: 1
Views: 1446
Reputation: 22323
You can use group_by
and summarise
from dplyr
to achieve the desired result. See below for the code.
# load required package
require(dplyr)
# function to calculate the confidence interval
CIfun <- function(v, probs = c(.025, .975)) {
quantile(boot(data = v, function(u,i) tb(u[i]), R = 999)$t, probs)
}
# using summarise from dplyr
dataframe %>% group_by(x) %>%
summarise(n = n(),
proportion = tb(vec),
`2.5%` = CIfun(vec, .025),
`97.5%`= CIfun(vec, .975))
Upvotes: 5