Search code examples
rfor-loopmatrixappendmatrix-multiplication

source r code, append specific value for each run. Or efficifiently pass through lapply or for loop


I am trying to effectively bootstrap the resultant allYears output by resampling the object A which is a list of matrices after each run of the for loop and append each run to a list. unfortunately the sample function draws randomly, and all I want to do is re-run object A sequentially before each new loop run and append the results to a list. Replicate doesn't re-run object A. Thanks in advance. See code below:

A <- lapply(1:4, function(x)  # construct list of matrices
  matrix(c(0, 0, 10,
           rbeta(1,5,4), 0, 0,
           0, rbeta(1,10,2), 0), nrow = 3,ncol=3, byrow = TRUE, ))

n <- c(1000,100,10)  # initial vector of abundances

nYears = 4  # define the number of years to project over

allYears <- matrix(0,nrow=3,ncol=nYears+1)  # build a storage array for all abundances

allYears[,1] <- n  # set the year 0 abundance   

i1 <- 2:ncol(allYears)

for(t in seq_along(i1)) {
  allYears[,i1[t]] <-  A[[t]] %*% allYears[,i1[t]-1]
}

Solution

  • Here I wrap in a function and replicate.

    library(plyr)
    set.seed(123)
    Stoch_Proj_Function <- function() {A <- lapply(1:4, function(x)  # construct list of matrices
      matrix(c(0, 0, 10,
               rbeta(1,5,4), 0, 0,
               0, rbeta(1,10,2), 0), nrow = 3,ncol=3, byrow = TRUE, ))
    
    n <- c(1000,100,10)  # initial vector of abundances
    
    nYears = 4  # define the number of years to project over
    
    allYears <- matrix(0,nrow=3,ncol=nYears+1)  # build a storage array for all abundances
    
    allYears[,1] <- n  # set the year 0 abundance   
    
    i1 <- 2:ncol(allYears)
    
    for(t in seq_along(i1)) {
      allYears[,i1[t]] <-  A[[t]] %*% allYears[,i1[t]-1]
    }
    
    final <- allYears
    }
    
    master_array <- replicate(10,Stoch_Proj_Function())
    master_list <- alply(master_array,3)