Reputation: 31
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!
Upvotes: 3
Views: 1442
Reputation: 1697
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
Upvotes: 3
Reputation: 6213
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
Upvotes: 5