The Wayback Machine - https://web.archive.org/web/20240720165757/https://www.geeksforgeeks.org/bootstrapping-in-r-programming/
Open In App

Bootstrapping in R Programming

Last Updated : 16 Dec, 2021
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Bootstrapping is a technique used in inferential statistics that work on building random samples of single datasets again and again. Bootstrapping allows calculating measures such as mean, median, mode, confidence intervals, etc. of the sampling. 

R – Bootstrapping

Following is the process of bootstrapping in R Programming Language: 

  • Select the number of bootstrap samples.
  • Select the size of each sample.
  • For each sample, if the size of the sample is less than the chosen sample, then select a random observation from the dataset and add it to the sample.
  • Measure the statistic on the sample.
  • Measure the mean of all calculated sample values.

Methods of Bootstrapping

There are 2 methods of bootstrapping: 

  • Residual Resampling: This method is also called as model-based resampling. This method assumes that model is correct and errors are independent and distributed identically. After each resampling, variables are redefined and new variables are used to measure the new dependent variables.
  • Bootstrap Pairs: In this method, dependent and independent variables are used together as pairs for sampling.

Types of Confidence Intervals in Bootstrapping

Confidence Interval (CI) is a type of computational value calculated on sample data in statistics. It produces a range of values or an interval where the true value lies for sure. There are 5 types of confidence intervals in bootstrapping as follows: 

  • Basic: It is also known as Reverse Percentile Interval and is generated using quantiles of bootstrap data distribution. Mathematically,

\left(2 \widehat{\theta}-\theta_{(1-\alpha / 2)}^{*}, 2 \widehat{\theta}-\theta_{(\alpha / 2)}^{*}\right)

where,
\alpha  represents confidence interval, mostly \alpha = 0.95
\theta^{*}  represents bootstrapped coefficients 
\theta_{(1-\alpha / 2)}^{*}  represents 1-\alpha / 2  percentile of bootstrapped coefficients 

  • Normal: Normal CI is mathematically given as,

\begin{array}{c} t_{0}-b \pm Z_{\alpha} \cdot \mathrm{se}^{*} \\ 2 t_{0}-t^{*} \pm Z_{\alpha} \cdot \mathrm{se}^{*} \end{array}
where,

t_{0}  represents a value from dataset t 
b is the bias of bootstrap estimate i.e.,  

\mathbf{b}=\mathbf{t}^{*}-\mathbf{t}_{\mathrm{o}}
Z_{\alpha}  represents 1-\alpha / 2  quantile of bootstrap distribution 
se^{*}  represents standard error oft^{*}

  • Stud: In studentized CI, data is normalized with center at 0 and standard deviation 1 correcting the skew of distribution.
  • Perc – Percentile CI is similar to basic CI but with different formula,

\left(\theta_{(\alpha / 2)}^{*}, \theta_{(1-\alpha / 2)}^{*}\right)

  • BCa: This method adjusts for both bias and skewness but can be unstable when outliers are extreme. Mathematically,

\left(\theta_{0}+\frac{\theta_{0}+\theta_{\alpha}}{1-a\left(\theta_{0}-\theta_{\alpha}\right)}, \theta_{0}+\frac{\theta_{0}+\theta_{(1-\alpha)}}{1-a\left(\theta_{0}-\theta_{(1-\alpha)}\right)}\right)

The syntax to perform bootstrapping in R programming is as follows:

Syntax: boot(data, statistic, R)

Parameters: 

  • data represents dataset
  • statistic represents statistic functions to be performed on dataset
  • R represents number of samples

To learn about more optional arguments of boot() function, use below command:

help("boot")

Example: 

R

# Library required for boot() function
install.packages("boot")
 
# Load the library
library(boot)
 
# Creating a function to pass into boot() function
bootFunc <- function(data, i){
df <- data[i, ]
c(cor(df[, 2], df[, 3]),
    median(df[, 2]),
    mean(df[, 1])
)
}
 
b <- boot(mtcars, bootFunc, R = 100)
 
print(b)
 
# Show all CI values
boot.ci(b, index = 1)

                    

Output: 

ORDINARY NONPARAMETRIC BOOTSTRAP
Call:
boot(data = mtcars, statistic = bootFunc, R = 100)


Bootstrap Statistics :
      original       bias    std. error
t1*  0.9020329 -0.002195625  0.02104139
t2*  6.0000000  0.340000000  0.85540468
t3* 20.0906250 -0.110812500  0.96052824


BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS
Based on 100 bootstrap replicates

CALL : 
boot.ci(boot.out = b, index = 1)

Intervals : 
Level      Normal              Basic         
95%   ( 0.8592,  0.9375 )   ( 0.8612,  0.9507 )  

Level     Percentile            BCa          
95%   ( 0.8534,  0.9429 )   ( 0.8279,  0.9280 )  
Calculations and Intervals on Original Scale
Some basic intervals may be unstable
Some percentile intervals may be unstable
Warning : BCa Intervals used Extreme Quantiles
Some BCa intervals may be unstable
Warning messages:
1: In boot.ci(b, index = 1) :
  bootstrap variances needed for studentized intervals
2: In norm.inter(t, adj.alpha) :
  extreme order statistics used as endpoints


Previous Article
Next Article

Similar Reads

Getting the Modulus of the Determinant of a Matrix in R Programming - determinant() Function
determinant() function in R Language is a generic function that returns separately the modulus of the determinant, optionally on the logarithm scale, and the sign of the determinant. Syntax: determinant(x, logarithm = TRUE, ...) Parameters: x: matrix logarithm: if TRUE (default) return the logarithm of the modulus of the determinant Example 1: # R
2 min read
tidyr Package in R Programming
Packages in the R language are a collection of R functions, compiled code, and sample data. They are stored under a directory called “library” in the R environment. By default, R installs a set of packages during installation. One of the most important packages in R is the tidyr package. The sole purpose of the tidyr package is to simplify the proc
14 min read
Get Exclusive Elements between Two Objects in R Programming - setdiff() Function
setdiff() function in R Programming Language is used to find the elements which are in the first Object but not in the second Object. Syntax: setdiff(x, y) Parameters: x and y: Objects with sequence of itemsR - setdiff() Function ExampleExample 1: Apply setdiff to Numeric Vectors in R Language C/C++ Code # R program to illustrate # the use of setdi
2 min read
Add Leading Zeros to the Elements of a Vector in R Programming - Using paste0() and sprintf() Function
paste0() and sprintf() functions in R Language can also be used to add leading zeros to each element of a vector passed to it as argument. Syntax: paste0("0", vec) or sprintf("%0d", vec)Parameters: paste0: It will add zeros to vector sprintf: To format a vector(adding zeros) vec: Original vector dataReturns: Vectors by addition of leading zeros Exa
1 min read
Clustering in R Programming
Clustering in R Programming Language is an unsupervised learning technique in which the data set is partitioned into several groups called clusters based on their similarity. Several clusters of data are produced after the segmentation of data. All the objects in a cluster share common characteristics. During data mining and analysis, clustering is
6 min read
Compute Variance and Standard Deviation of a value in R Programming - var() and sd() Function
var() function in R Language computes the sample variance of a vector. It is the measure of how much value is away from the mean value. Syntax: var(x) Parameters: x : numeric vector Example 1: Computing variance of a vector # R program to illustrate # variance of vector # Create example vector x &lt;- c(1, 2, 3, 4, 5, 6, 7) # Apply var function in
1 min read
Compute Density of the Distribution Function in R Programming - dunif() Function
dunif() function in R Language is used to provide the density of the distribution function. Syntax: dunif(x, min = 0, max = 1, log = FALSE) Parameters: x: represents vector min, max: represents lower and upper limits of the distribution log: represents logical value for probabilities Example 1: # Create vector of random deviation u &lt;- runif(20)
1 min read
Compute Randomly Drawn F Density in R Programming - rf() Function
rf() function in R Language is used to compute random density for F Distribution. Syntax: rf(N, df1, df2) Parameters: N: Sample Size df: Degree of Freedom Example 1: # R Program to compute random values # of F Density # Setting seed for # random number generation set.seed(1000) # Set sample size N &lt;- 20 # Calling rf() Function y &lt;- rf(N, df1
1 min read
Data Handling in R Programming
R Programming Language is used for statistics and data analytics purposes. Importing and exporting of data is often used in all these applications of R programming. R language has the ability to read different types of files such as comma-separated values (CSV) files, text files, excel sheets and files, SPSS files, SAS files, etc. R allows its user
5 min read
Return a Matrix with Lower Triangle as TRUE values in R Programming - lower.tri() Function
lower.tri() function in R Language is used to return a matrix of logical values with lower triangle as TRUE. Syntax: lower.tri(x, diag) Parameters: x: Matrix object diag: Boolean value to include diagonal Example 1: # R program to print the # lower triangle of a matrix # Creating a matrix mat &lt;- matrix(c(1:9), 3, 3, byrow = T) # Calling lower.tr
1 min read
Article Tags :
three90RightbarBannerImg