One of the things that blew my mind the first time I learned about it is bootstrapping. Although very counterintuitive at first glance, it makes perfect sense to estimate the accuracy of your sample estimates, given that you have a representative sample. In this blog post I explain how you can calculate confidence intervals for any difference in estimate between two samples, using the simpleboot R package.

First we load in the packages. I load in the simpleboot package for performing the two-sample bootstrap and I will use ggplot2 for demonstration.

library(simpleboot)
library(ggplot2)

Next, I generate two samples of data where we can perform the bootstrap on. I also plot their densities to show how these two samples differ from each other.

The bootstrapped object is a list. The most interesting elements are the initial sample mean (t0), the sample differences (t), the amount of resamples (R), the data, the seed, etc.

In the next part of the code, I turn the vector of sample differences into a data frame so that I can use it in ggplot. I plot the differences as a histogram and add three vertical lines: the initial sample mean and the confidence interval boundaries (p = 0.05).

Given this information we got from bootstrapping our samples, we can reject the null hypothesis that both means are the same. On a p = 0.05 level, we can see that both samples have a different mean.

Great success!

Say thanks, ask questions or give feedback

Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.

3 thoughts on “How to do a two-sample bootstrap of the mean in R”

Calvin Banvelos

That is a very good tip especially to those fresh to the blogosphere. Short but very accurate info… Thank you for sharing this one. A must read article!

Hey there! I just wish to offer you a huge thumbs up for the great information you have got here on this post. I will be returning to your website for more soon.

That is a very good tip especially to those fresh to the blogosphere. Short but very accurate info… Thank you for sharing this one. A must read article!

Thanks Calvin!

Hey there! I just wish to offer you a huge thumbs up for the great information you have got here on this post. I will be returning to your website for more soon.