5.14 Storing AFs in a vector

To plot how the AF changes over time, we can store the AF at each generation in a vector.

Vectors R’s version of a list, and are formed with the c() function, which stands for “combine”:

my_vec <- c(0.5, 0.6)
my_vec
## [1] 0.5 0.6

You can append elements to a vector called my_vec by running: my_vec <- c(my_vec, new_element).


Modify the code block with our for loop to create a vector for storing allele frequencies, and then append the updated AF to it every generation.

We need to create the vector before the for loop, and then append to the vector within the for loop.

Ne <- 100
freq <- 0.5
# create vector to store AFs in
freq_vector <- freq

for (i in 1:20) {
  new_freq <- rbinom(n = 1, size = Ne, prob = freq) / Ne
  # add new freq to the AF vector
  freq_vector <- c(freq_vector, new_freq)
  freq <- new_freq
}

freq_vector
##  [1] 0.50 0.52 0.64 0.63 0.65 0.63 0.61 0.68 0.68 0.65 0.63 0.63 0.64 0.62 0.57
## [16] 0.60 0.61 0.63 0.64 0.65 0.68