5.18 Creating a Wright-Fisher function

We want our function to take in parameters for the starting allele frequency, population size, and number of generations to simulate. It should return the sim_results dataframe so that we can plot the allele frequency trajectory.

To write a function, we can put the code that we just wrote into the function body:

run_sim <- function(Ne, freq, generations) {
  
  # note how we don't define our initial parameters for Ne, freq, etc.
  # because we're passing in those parameters as arguments
  
  freq_vector <- freq
  for (i in 1:generations) {
    new_freq <- rbinom(n = 1, size = Ne, prob = freq) / Ne
    freq_vector <- c(freq_vector, new_freq)
    freq <- new_freq
  }
  
  # convert vector of AFs into a tibble for plotting
  sim_results <- tibble(afs = freq_vector,
                        gen = 1:(generations+1))
  
  # return the tibble of AFs, so that we can access the results
  return(sim_results)
}