我試圖通過重新采樣物件 A 來有效地引導生成的 allYears 輸出,該物件 A 是每次運行 for 回圈后的矩陣串列,并將每次運行附加到串列中。不幸的是,示例函式是隨機繪制的,我要做的就是在每個新回圈運行之前按順序重新運行物件 A 并將結果附加到串列中。復制不會重新運行物件 A。提前致謝。請參見下面的代碼:
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]
}
uj5u.com熱心網友回復:
如果您想在每次迭代之前重新采樣并更改 A 創建中的一些引數,我建議如下:
get_A <- function(parameter1){
a <- lapply(1:4, function(x) # construct list of matrices
matrix(c(0, 0, paramter1, # here I replace 10 with paramter10
rbeta(1,5,4), 0, 0,
0, rbeta(1,10,2), 0), nrow = 3,ncol=3, byrow = TRUE, ))
return(a)
}
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)) {
A <- get_A(10*t)
allYears[,i1[t]] <- A[[t]] %*% allYears[,i1[t]-1]
}
uj5u.com熱心網友回復:
在這里,我包裝了一個函式并進行了復制。
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/418743.html
標籤:
上一篇:for回圈似乎根本沒有運行
