0

I'm trying to populate an matrix via a loop. Given a vector of values and an empty matrix;

n <- c(seq(10,100,10))
out <- matrix(ncol=1, nrow=length(n))

running this simple loop as an example;

for(i in n){
  dostuff <- i*2
  out[i,1] <- dostuff
}

gives the error message

Error in[<-(tmp, i, 1, value = dostuff) : subscript out of bounds,

as the interval within the vector that the loop is based on is larger than 1 and therefore does not fit the 1:10 index of the matrix rows. Removing i from the out row index only repeats the result of the last iteration :

for(i in n){
  dostuff <- i*2
  out[,1] <- dostuff
  }

There is obviously something fundamental about loops that I don't understand. I have looked, e.g. here and here, but have not been able to find a good solution. This is the result I'm looking for:

      [,1]
 [1,]   20
 [2,]   40
 [3,]   60
 [4,]   80
 [5,]  100
 [6,]  120
 [7,]  140
 [8,]  160
 [9,]  180
[10,]  200
M.Teich
  • 575
  • 5
  • 22
  • `1:n`, `for(i in 1:n)` and without loop that would be `out[, 1] <- n*2` – Ronak Shah Apr 18 '19 at 14:14
  • 3
    Why not just `matrix(data = n*2, ncol = 1)`? Should be faster. – JasonAizkalns Apr 18 '19 at 14:15
  • @JasonAizkalns That is a nice option. Please make it as an answer – akrun Apr 18 '19 at 14:23
  • @JasonAizkalns yes, that is of course much more elegant, but this is just a simplified example. I do a lot of operations in the actual loop (not shown here) and need to write the results into a matrix. However, due to the mismatch between the vector interval (10) and the row index interval (1), I have had problems doing so. – M.Teich Apr 18 '19 at 14:27

0 Answers0