Getting error code "number of items to replace is not a multiple of replacement length"

This is the code I'm trying to run and it worked in the past but now I am getting an error on the "Nt[ ,1] <- N0" saying, number of items to replace is not a multiple of replacement length. I don't know how to resolve this.
'''r
L <- matrix(c(0, 2.5, 5.0, 5.0,
0.20, 0, 0, 0,
0, 0.35, 0, 0,
0, 0, 0.45, 0,
0,0,0,0.25),
byrow=T, nrow=5, ncol=4)
L
N0 <- matrix(c(100, 30, 20, 10), byrow=T, nrow=4, ncol=1)
N0
N1 <- L%*%N0
N1
n.years <- 25
Nt <- matrix(NA, nrow=nrow(L), ncol=n.years)
Nt
Nt[ ,1] <- N0
Nt

for(t in 2:n.years){
Nt[ ,t] <- L%*%Nt[ ,t-1]
}
print(round(Nt[ ,1:25], digits=0))
Nproj <- apply(Nt, 2, sum)
plot(1:length(Nproj), Nproj, ylim=c(100,300), ylab="N", xlab="Years", type="l", lwd=2)
plot(1:n.years, Nt[1,], ylim=c(0,300), ylab="N", xlab="Years", type="l", col=1, lwd=2)
lines(1:n.years, Nt[2,], type="l", col=2, lwd=2)
lines(1:n.years, Nt[3,], type="l", col=3, lwd=2)
lines(1:n.years, Nt[4,], type="l", col=4, lwd=2)
lines(1:n.years, Nt[5,], type="1", col=5, lwd=2)
L_eigen <- eigen(L)
L_eigen
lambda <- Re(L_eigen$values[1])
lambda

Maybe I'm missing something, but I don't see how your code can work unless L is a square matrix. Most of the columns of Nt are filled in the for loop with
Nt[ ,t] <- L %*% Nt[ ,t-1]. The number of rows in the result of L %*% Nt[ ,t-1] is determined by the number of rows in L. So, nrow(L) == nrow(Nt), and you have defined Nt to meet that requirement. But for L %*% Nt[ ,t-1] to work, the number of columns in L has to match the number of rows in Nt. So, L is square.

Also, you never use N1 and its name makes me suspect that the line Nt[ ,1] <- N0 should be Nt[ ,1] <- N1.

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.