Fabled
Fabled

Reputation: 79

For loop does not index properly - placing results in a matrix from for loop

So I'm trying to do 10 different bootstrap simulations, with sample sizes 10,20,...,100. So I've created a vector containing these sample sizes and then iterate over them using a for loop as shown below.

The while loop just computes the mean of the bootstrap sample 1800 times, and stores all these values in the vector K. This means I should get 10 different of these vectors K and finally for every j, i want to place each K in one column in the matrix L.

The problem is that I get the matrix L, but all the columns are identical. There is something wrong with the loop and I can't figure out what it is.

Any input is appreciated. Here is my code:

N = 1800
i = 0
K = vector("numeric", 1800L)
L = matrix(nrow = 1800, ncol = 10)
ListValues = c(10,20,30,40,50,60,70,80,90,100)

for (j in 1:10){
  while (i <= N){
    x = sample(Data, ListValues[j])
    K[i] = mean(x)
    i = i + 1
  }
  L[,j] = K
}
print(L)

Result:

> print(L)
            [,1]     [,2]     [,3]     [,4]     [,5]     [,6]     [,7]     [,8]     [,9]    [,10]
   [1,] 3.669182 3.669182 3.669182 3.669182 3.669182 3.669182 3.669182 3.669182 3.669182 3.669182
   [2,] 3.764834 3.764834 3.764834 3.764834 3.764834 3.764834 3.764834 3.764834 3.764834 3.764834
   [3,] 4.324697 4.324697 4.324697 4.324697 4.324697 4.324697 4.324697 4.324697 4.324697 4.324697
   [4,] 4.473386 4.473386 4.473386 4.473386 4.473386 4.473386 4.473386 4.473386 4.473386 4.473386

Upvotes: 2

Views: 345

Answers (2)

jogo
jogo

Reputation: 12559

Here is a shorter version:

N <- 1800L
L <- matrix(nrow = N, ncol = 10)
ListValues <- c(10,20,30,40,50,60,70,80,90,100)
for (j in 1:10) L[,j] <- replicate(N, mean(sample(Data, ListValues[j])))

or even shorter (but not faster):

N <- 1800L
ListValues <- c(10,20,30,40,50,60,70,80,90,100)
L <- sapply(1:10, function(j) replicate(N, mean(sample(Data, ListValues[j]))))

Upvotes: 3

karen
karen

Reputation: 812

Try this:

N = 1800
i = 0
K = vector("numeric", 1800L)
L = matrix(nrow = 1800, ncol = 10)
ListValues = c(10,20,30,40,50,60,70,80,90,100)

for (j in 1:10){
  i = 0
  while (i <= N){
    x = sample(Data, ListValues[j])
    K[i] = mean(x)
    i = i + 1
  }
  L[,j] = K
}
print(L)

Upvotes: 1

Related Questions