see this original post for more details Sequentially multiply matrices from a list by a vector at time t-1 (recursively)
am trying to accomplish the same thing, this time with sublists of matrices contained within a list, which is then matrix multiplied recursively by a list of storage arrays. Additionally, the commented out section in the forloop, I’m trying to place a cap on the resulting 4th row in all resultant list items. Help extending that concept would also be appreciated. thanks
library(plyr)
library(popbio)
library(ggplot2)
library(tidyr)
library(dplyr)
library(reshape2)
library(simpleboot)
library(boot)
library(reshape)
library(vctrs)
# setting seed for replication purposes and creating function to project. replicating with bootstrap
set.seed(123)
# vector of egg survival morts
egg.to.fry.s <- vec_rep(c(seq(from = 0.40, to = 0.89,by=0.01)),10)
# vector of fry survival morts
fry.to.one.s <- vec_rep(c(seq(from = 0.30, to = 0.79,by=0.01)),10)
# one.to.two rates
one.to.two.s <- rbeta(500,5,4)
A <- lapply(1:500, function(x) # construct list of matrices
matrix(c(0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0), nrow = 4,ncol=4, byrow = TRUE, ))
Anew <- A
for(t in 1:length(Anew)) {
Anew[[t]][2,1] <- egg.to.fry.s[t]
Anew[[t]][3,2] <- fry.to.one.s[t]
Anew[[t]][4,3] <- one.to.two.s[t]
}
AnewSplit <- split(Anew, rep(1:10, each = 50)) # split list into lists to represent each sim
n <- c(10000,1000,100,10) # initial vector of abundances
nYears = 50 # define the number of years to project over
allYears <- matrix(0,nrow=4,ncol=nYears+1) # build a storage array for all abundances
allYears[,1] <- n # set the year 0 abundance
allYearsarray<-replicate(10,allYears)
allYearslist <- alply(allYearsarray,3)
i1 <- length(allYearslist)
i2 <- 2:51
# matrix multiply each list of 50 sequentially in AnewSplit * each list in allYears list and each column - 1
for(t in 1:i1) {
for(j in seq_along(i2)){
allYearslist[[t]][,i2[j]] <- AnewSplit[[t]]%*% allYearslist[[t]][,i2[j]-1]
# allYearslist[4,i1[t]] <- ifelse (allYearslist[4,i1[t]] > 100000, 100000, allYearslist[4,i1[t]]) # to add density dependence to 4th row
}
}