Repeat the re-sampling function for 1000 times ? Using lapply?
Asked Answered
T

1

12

Please me out! I appreciate any helps ! Thanks!

I have trouble on repeat doing re-sampling for 1000 times. I tried using replicate() to do that but it's not working. Is there any other method to do that? Can anyone show me if this maybe done by using lapply? Following is my code:

#sampling 1000 betas0 & 1 (coefficients) from the data
get.beta=function(data,indices){ 
  data=data[indices,] #let boot to select sample
  lm.out=lm(y ~ x,data=data)
  return(lm.out$coefficients)
}
n=nrow(data)
get.beta(data,1:n)

bootcoe=boot(data,get.beta,R=1000) #generate 1000 random samples
head(bootcoe$t) #look at the betas

From the above code I can get 1000 betas0 & 1 by random sampling the data. And I would like to do that 1000 times to get different betas. How should I do that besides replicate()?

Trask answered 10/12, 2013 at 9:17 Comment(4)
So replicate(1000, {your_codez}) isn't working?Scamp
ya, I have tried rep(1000, function())but can't get the result.Trask
I didn't say to use function(). You should use curly braces.Scamp
FYI, replicate is a wrapper for the common use of sapply for repeated evaluation of an expression. sapply is itself a user-friendly version and wrapper of lapply that returns a vector or a matrix instead of a list.Sedan
M
29

This is more of an extended comment where I demonstrate that replicate should work. Here's an example of a CLT. Just replace your lines what's between the curly braces.

x <- replicate(1000, {
  mm <- runif(10)
  mean(mm)
  })
hist(x)

enter image description here

Maw answered 10/12, 2013 at 9:34 Comment(3)
Thanks @Roman. So in my case, which should I put inside the {} ? I tried put get.beta but it gives errors, and having bootcoe runs for a long time. Putting both get.beta and bootcoe gives error again.Trask
Also, why there is mean(mm) at the end? Thanks !Trask
@Trask the last line is the result of your function. You should put between braces the things you want to be evaluated.... n times.Scamp

© 2022 - 2024 — McMap. All rights reserved.