Kristen Cyr
Kristen Cyr

Reputation: 726

How to make bootstrap distribution in R?

I'm trying to calculate the bootstrap distribution of an estimated slope in R using the boot function. I have made a function which calculates the slope and it's standard error. Now I need to generate a bootstrap distribution and then append this distribution with the slope of my line into a vector. Here is my sample data

# rm(list=ls())
set.seed(999123)
x = c(1,1.5,2,3,4,4.5,5,5.5,6,6.5,7,8,9,10,11,12,13,14,15)
y = c(21.9,27.8,42.8,48.0,52.5,52.0,53.1,46.1,42.0,39.9,38.1,34.0,33.8,30.0,26.1,24.0,20.0,11.1,6.3)

data = data.frame(x=x, y=y)

this is the code I used to build the function to give me the slope of the line and std. error

b1=function(data,index){
  x=data$x[index]
  y=data$y[index]
  lmout=lm(y~x)
  b1=coef(lmout)[2]
  return(b1)}

library(boot)
data=data.frame(x=x,y=y)

Nboot = 20
mybdone = boot(data,b1,R=Nboot)
mybdone

Does anyone know how to make a bootstrap distribution that I can use to eventually get the bootstrap distribution of the estimated slope?

Upvotes: 1

Views: 456

Answers (1)

dario
dario

Reputation: 6483

Your code is almost there... If we check the boot documentation with ?boot and look for the part where it describes the return value (in R docs confusingly titled with just Value) we find this entry:

t A matrix with sum(R) rows each of which is a bootstrap replicate of the result of calling statistic.

Which means we only have to call

mybdone$t

To get:

           [,1]
 [1,] -2.470016
 [2,] -1.763517
 [3,] -1.856894
 [4,] -2.189789
 [5,] -1.276630
 [6,] -2.010069
 [7,] -2.002160
 [8,] -2.193305
 [9,] -1.840872
[10,] -3.810425
[11,] -2.585354
[12,] -2.836741
[13,] -1.869082
[14,] -3.209472
[15,] -1.041906
[16,] -2.167952
[17,] -2.807697
[18,] -1.445792
[19,] -3.355852
[20,] -1.756974

Which we can use for plotting or any computations. There is no shame in having to refer to Rs excellent help system by calling ?name_of_a_function to look up how the arguments or, as in this case, the return values are structured. I need to look stuff up this way all the time!

Upvotes: 1

Related Questions