Making a matrix from for loops

Dear all,

I am new to Rstudio and I was wondering on how to create a matrix from the result created in for loops. I have done 5000 simulations using the R package StMoMO which resulted in a data with a total of 5000 simulations x 90 ages x 33 years. I wanted to extrapolate the data to get values for ages above 90 for each year and each simulation. However, I am having difficulties on how to get the result of the for loop into a matrix. This is what I have done so far:

LCfit <- fit(LC,data = JPNStf, ages.fit = age,years.fit = years)
LCsim <- simulate(LCfit, nsim = 5000, h = 33)

Ms <- LCsim$rates
LnMs <- log(Ms)
LnMst <- aperm(LnMs,c(3,1,2))

#Extrapolation for ages 90-109
for(n in 1:5000){
  c <- LnMst[n,90,]-LnMst[n,89,]
  d <- ((21*c)-log(0.7)+LnMst[n,89,])/210
  lnm90 <- c-d+LnMst[n,90,]
  lnm91 <- c-(2*d)+lnm90
  lnm92 <- c-(3*d)+lnm91
  lnm93 <- c-(4*d)+lnm92
  lnm94 <- c-(5*d)+lnm93
  lnm95 <- c-(6*d)+lnm94
  lnm96 <- c-(7*d)+lnm95
  lnm97 <- c-(8*d)+lnm96
  lnm98 <- c-(9*d)+lnm97
  lnm99 <- c-(10*d)+lnm98
  lnm100 <- c-(11*d)+lnm99
  lnm101 <- c-(12*d)+lnm100
  lnm102 <- c-(13*d)+lnm101
  lnm103 <- c-(14*d)+lnm102
  lnm104 <- c-(15*d)+lnm103
  lnm105 <- c-(16*d)+lnm104
  lnm106 <- c-(17*d)+lnm105
  lnm107 <- c-(18*d)+lnm106
  lnm108 <- c-(19*d)+lnm107 
}

What I wanted to do is to put the results of the simulated lnm90 to lnm108 in a matrix. Do you have any advice? Thank you in advance for your help. I deeply appreciate it.

Here is a completely generic example on how to fill a matrix using for-loops in R:

m = 100
n = 20
o = matrix(data = NA, nrow = m, ncol = n)
for( i in 1:m ){
  for( j in 1:n ){
    o[i,j] = rnorm(n = 1)
  }
}

Or filling by row:

m = 100
n = 20
o = matrix(data = NA, nrow = m, ncol = n)
for( i in 1:m ){
    o[i,] = rnorm(n = n)
}

Or, as you generally would in R, avoiding the loop altogether:

m = 100
n = 20
o = matrix(data = rnorm(n = m*n), nrow = m, ncol = n)

Hope it helps :slightly_smiling_face:

2 Likes

Hi Leon,

Thank you very much for your advice. It's very helpful.

You're welcome. If my answer is the "solution", please mark is as such :+1: :slightly_smiling_face:

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.