# Leslie Matrix introduction t <- 50 # number of years ages <- 4 A <- matrix(0, nrow = ages, ncol = ages) A[1,] <- c(0, 0.5, 1, 2) A[2,1] <- 0.5 A[3,2] <- 0.8 A[4,3] <- 0.6 A # Build a matrix for storing population output from 'for loop' # 'n' will store the number of individuals as follows: # - each row represents a year # - each column represents an age (stage) class # - value in row 2, column 3 = the number in yr 2 for age class 3 n <- matrix(0, t, ages) # Add row and column names to n to help us keep track of # what's stored where rownames(n) <- paste("yr", 1:t, sep = ".") colnames(n) <- paste("age", 1:ages, sep = ".") n[1, ] <- rep(10, ages) head(n) # Project population forward and store output for (yr in 2:t) { n[yr, ] <- A %*% n[(yr - 1), ] # %*% = matrix multiply } # 'N' stores the population totals for each year N <- apply(n, 1, sum) # calculate the row sums of 'n' # 'lambda' will hold the annual growth rates lambda <- N[2:t] / N[1:(t - 1)] # Store age distributions age.structure <- n/N # you can use the next line to see the rounded values if you like round(age.structure, 3) # Store graphics settings opar <- par() # make a copy of current settings # Set graphics parameters to be 3 rows of plots in 1 column # and set margins (bottom, left, top, right) par(mfrow = c(3, 1), mar = c(4, 4.5, 1, 1)) matplot(1:t, n, 'o', xlab = "Year", ylab = "Pop Size by Age") matplot(1:t, log(n), 'o', xlab = "Year", ylab = "ln(Pop Size) by Age") plot(1:(t - 1), lambda, 'o', xlab = "Year") # Change graphics parameters to be 2 rows of plots in 1 column par(mfrow = c(2, 1), mar = c(4, 4.5, 1, 1)) # Set graphics window to 2 rows of plots in 1 column matplot(1:10, n[1:10, ], "o", xlab = "Year", ylab = "Pop Size by Age") matplot(1:t, age.structure, "o", xlab = "Year", ylab = "Ppn by Age") # restore graphics parameters to defaults par(opar) # might produce warnings #========================================# # Functions used this week include: # # '%*%' # # 'apply' # # 'round' # # 'matplot' # # 'par' # #========================================#