3. While we could use a loop to calculate the summed value for each value of n, a
faster method is the use of the R function apply (whenever possible object-
oriented programming should be used).
4. Finally the results are plotted using the R function plot.
rm(list¼ls()) # remove all objects from memory
# Function to calculate the summation of equation (2.19)
SUMMATION <- function(n)
{
x <- 1 # As before we set x ¼ 1
Age <- seq(from¼1, to¼n) # Sequence from 1 to n
Wt <- 4*x*exp(-(1þ0.5*x)*Age) # Vector of fitness at age t
return(sum(Wt)) # Return the summed value
}
# MAIN PROGRAM
nmax <- 20 # Set maximum value for n
n <- matrix(seq(from¼1, to¼nmax)) # Vector of n values
W <- apply(n,1,SUMMATION) # Apply function SUMMATION to each row
# Plot W vs n using ’l’ to designate a line
# las¼number orientation on axes, lwd ¼ line width
plot(n,W,type¼’l’, xlab¼’Age, n’, ylab¼’Weight, Wt’, las¼1,
lwd¼3)
The summation quickly approaches its asymptotic value (Figure 2.2) and setting
the maximum age at 20 should be adequate for all reasonable values of x. Now we
change the summation function to sum for different values of x and plot the result
(Figure 2.3):
rm(list¼ls()) # Remove all objects from memory
# Function to calculate the summation as a function of x
SUMMATION <- function(x)
{
Age <- seq(from¼1, to¼20) # Sequence from 1 to 20
Wt <- 4*x*exp(-(1þ0.5*x)*Age) # Vector of fitness at age t
return(sum(Wt)) # Return the summed value
}
# MAIN PROGRAM
x<- matrix(seq(from¼
0, to¼5
, length¼100)) # Vector from 0-5 of length 100
W <- apply(x,1,SUMMATION) # Apply function SUMMATION to each row
# Plot W vs x using ’l’ to designate a
line
# las¼number orientation on axes, lwd
¼ line width
plot(x,W,type¼’l’, xlab¼’Body size, x’, ylab¼’Fitness, W’,
las¼1,lwd¼4)
MATLAB CODE: See Section 2.18.4.
78 MODELING EVOLUTION