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