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