5.17 Simulating different parameters with a function
It would be nice to be able to run our Wright-Fisher simulation with different parameters – like different starting allele frequencies, population sizes, etc. – without having to edit the for loop code every time. We can use a function to generalize the code above so we can easily re-run it.
The structure of an R function
You’ve already encountered many functions in R, even if you didn’t realize it at the time - rbinom
, ggplot
, and print
are all examples of functions. An R function has four parts:
<Name> <- function(<Argument(s)>) {
<Body>
<return()>
}
- Name − The function is stored in your R environment as an object with this name, and you use the name to call it
- Argument(s) − Optional; input values that the function performs operations on
- Body − The code that describes what the function does
- Return − Optional; a
return
statement allows the function to return a value to the user. Without a return statement, you won’t be able to access the function’s output
Here’s an example function that takes in three parameters for running rbinom
, and returns the output of rbinom
.
binom_sim <- function(myN, mySize, myProb) {
output <- rbinom(myN, mySize, myProb)
return(output)
}
How do I know when to use a function?
Functions are useful whenever you have code that you want to run multiple times with slightly different parameters. If you find yourself copying over code several times and changing just a few things, you should consider writing a function instead.