基本上,它在标题中。 尽管有更多详细信息,但我有四个需要按矩阵组织的参数集,我按一个列表(Alphaset)来组织,每个参数都有4个变量。但是我需要将特定变量调用到一个循环中,在该循环中它将经过一个方程式并给我一个图。
我和我对R的较差知识尝试了导致效率低下的不同组合,例如“ Alphaset [2,1,1]”或“ Alphaset [2(1,1)]” (这是一个示例,我要在其中显示第二个矩阵的第一行第一列的变量。)
#Parameters set on types (lambda 1, lambda 2, alphas)
Lambda1set<-c(5,5,3,3.2)
Lambda2set<-c(4,4,5,3)
Alphaset<-list(matrix(c(0.01, 0.007, 0.0045, 0.01),ncol = 2, byrow = TRUE),
matrix(c(0.01, 0.003, 0.007, 0.01),ncol = 2, byrow = TRUE),
matrix(c(0.01, 0.0055, 0.003, 0.01),ncol = 2, byrow = TRUE),
matrix(c(0.005, 0.005, 0.0045, 0.004),ncol = 2, byrow = TRUE))
#Creating vectors
TimeVec<-seq(0,years,1)
N1<-matrix(0,4,years+1)
N2<-matrix(0,4,years+1)
#INITIALIZATION
N0 <- 40
N1[1] <-N0
N2[1] <-N0
for (t in 1:years){
for(i in 1:4){
N1[i,t+1]<-(Lambda1set[i]*N1[i,t])/(1+alphs[1,1]*N1[i,t]+alphs[1,2]*N2[i,t])
N2[i,t+1]<-(lambda2set[i]*N2[i,t])/(1+alphs[2,1]*N1[i,t]+alphs[2,2]*N2[i,t])
}
}
plot(TimeVec,N1,type="l",xlab='Time (years)',ylab='Population Density',col='blue',
lwd = 2,ylim = c(0,400))
在这里您可以在方程式中看到“ alphs [....]”代表我要使用的每个i矩阵中的哪个变量。
但是我该如何称呼我的矩阵列表?
答案 0 :(得分:0)
只需定义alphs
变量,如下所示:
alphs <- Alphaset[[i]]
在21行之后:for(i in 1:4){
答案 1 :(得分:0)
喜欢吗?
years <- 10
Lambda1set<-c(5,5,3,3.2)
Lambda2set<-c(4,4,5,3)
Alphaset<-list(matrix(c(0.01, 0.007, 0.0045, 0.01),ncol = 2, byrow = TRUE),
matrix(c(0.01, 0.003, 0.007, 0.01),ncol = 2, byrow = TRUE),
matrix(c(0.01, 0.0055, 0.003, 0.01),ncol = 2, byrow = TRUE),
matrix(c(0.005, 0.005, 0.0045, 0.004),ncol = 2, byrow = TRUE))
dat <- lapply(1:length(Alphaset), function(i) {
list(Lambda1=Lambda1set[i], Lambda2=Lambda2set[i], alphs=Alphaset[[i]])
})
#Creating vectors
TimeVec<-seq(0,years,1)
N1<-matrix(0,4,years+1)
N2<-matrix(0,4,years+1)
#INITIALIZATION
N0 <- 40
require(dplyr)
require(ggplot2)
lapply(seq_along(dat), function(i) {
dati <- dat[[i]]
N1 <- array(N0, dim=c(years+1))
N2 <- array(N0, dim=c(years+1))
for (t in 1:years) {
N1[t+1]<-(dati$Lambda1*N1[t])/(1+dati$alphs[1,1]*N1[t]+dati$alphs[1,2]*N2[t])
N2[t+1]<-(dati$Lambda2*N2[t])/(1+dati$alphs[2,1]*N1[t]+dati$alphs[2,2]*N2[t])
}
return(data.frame(i=i, Time=TimeVec, N1=N1, N2=N2))
}) %>%
bind_rows() %>%
mutate(i=factor(i)) %>%
gather("Variable", "Value", -Time, -i) %>%
ggplot(aes(x=Time, y=Value, color=Variable)) +
geom_line() +
ylab("Population Density") +
theme_bw() +
facet_grid(i~.)