Reputation: 141
I am trying to sample with replacement with a slight twist. I want to sample a list, vector, etc... 5 times and sum that. And replace the 5 sampled values, and do this 1000 times.
x<- 1:1000
samp <- matrix(NA, ncol = 1, nrow = 1000)
for(i in length(x)){
samp[i,] <- sum(sample(x,5,replace = TRUE))}
What I cant figure out is why this loop isnt working
Upvotes: 2
Views: 663
Reputation: 37879
You missed 1:
in front of length(x)
(i.e. from 1 to length of x by 1). Your code should be like this:
x<- 1:1000
samp <- matrix(NA, ncol = 1, nrow = 1000)
for(i in 1:length(x)){
samp[i,] <- sum(sample(x,5,replace = TRUE))}
Which works great:
> str(samp)
int [1:1000, 1] 2715 2312 3180 1364 2851 2429 2888 2381 2772 2317 ...
Also, for-loops
have a bad reputation of being slow in R so you might want to consider other ways of looping like using the C++
way with (for example) replicate
like this:
Define the function:
myfunc <- function(x) {
sum(sample(x,5,replace = TRUE))
}
And then use it like this:
x <- 1:1000
mymat <- matrix(replicate(1000, myfunc(x)), ncol=1)
> str(mymat)
int [1:1000, 1] 2481 2236 2492 1759 1905 3243 2606 2624 3013 2309 ...
Upvotes: 2