Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap Program in R

Tags:

r

I'm having the following error in my bootstrap program in R. Does anyone know how to fix this?

> local({pkg <- select.list(sort(.packages(all.available = TRUE)),graphics=TRUE)
+ if(nchar(pkg)) library(pkg, character.only=TRUE)})

> library(boot)

> RH = c(20, 15, 15, 20, 20, 25, 30, 30, 35, 35, 40, 40, 40, 40, 45, 50, 50, 50, 60, 60, 70, 20, 30, 35, 35, 35, 35, 45, 45, 45, 45, 50, 50, 50, 50, 55, 65, 65, 65, 65, 75, 75, 80)
> 
> results <- boot(data=RH, mean, R=1000)


Error in mean.default(data, original, ...) : 

  'trim' must be numeric of length one

Thanks!

like image 553
patchi0423 Avatar asked Jun 21 '26 01:06

patchi0423


2 Answers

From ?boot your statistic requires two parameters, one for the data and one for the index.

This function calculates the sample mean based on the indices of the vector.

samp_mean <- function(x, i) {
  mean(x[i])
}

And the function call with samp_mean instead of mean

results <- boot(data=RH, samp_mean, R=1000)
results

ORDINARY NONPARAMETRIC BOOTSTRAP


Call:
boot(data = RH, statistic = samp_mean, R = 1000)


Bootstrap Statistics :
    original      bias    std. error
t1* 44.30233 -0.04430233    2.610505
like image 143
Whitebeard Avatar answered Jun 23 '26 15:06

Whitebeard


The second argument to mean.default is trim, and boot is passing to mean a vector of indices as argument 'trim' which it is not expecting and quite rightly throws this error. Write a wrapper to mean, that accepts two arguments, the first as a data vector and the second as a permuted index, then use these to form a call to mean, here our wrapper function mean.fun does this (note we turn on removing NA's by default otherwise it wouldn't work)

library(boot)
RH <- c(20, 15, 15, 20, 20, 25, 30, 30, 35, 35, 40, 40, 40, 40, 45, 50, 50, 50, 60, 60, 70, 20, 30, 35, 35, 35, 35, 45, 45, 45, 45, 50, 50, 50, 50, 55, 65, 65, 65, 65, 75, 75, 80)
mean.fun <- function(dat, idx) mean(dat[idx], na.rm = TRUE) 
boot.result <- boot(RH, mean.fun, R=1000, sim="ordinary") 
boot.result

The Result:

ORDINARY NONPARAMETRIC BOOTSTRAP


Call:
boot(data = RH, statistic = mean.fun, R = 1000, sim = "ordinary")


Bootstrap Statistics :
    original    bias    std. error
t1* 44.30233 0.0694186    2.521452
like image 31
Ashraf Sarhan Avatar answered Jun 23 '26 16:06

Ashraf Sarhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!