Writing More Complex Functions

Let's start writing more complex functions.

Building in arguments

First, let’s add a single argument to specify the number of trials we want to simulate. In our original function, we specified that we wanted to run 10 trials. But why should that be fixed? Perhaps we want to explore how our ability to detect a difference in our predators’ changes with the number of trials we run. We’ll point out here that this is what a power analysis does, but we’re building it from the ground up.

Single argument functions

In the following code, we’ve specified a single argument: the number of trials we want to simulate running. Then in the code, we’ve used the name of that argument, numTrials, as the placeholder for everywhere we would have previously specified running 10 trials. We make the Trial column of the data frame go from 1 until whatever number numTrials is, and we run each rbinom() function for as many times as numTrials is run. However, since the size of our data frame will change with the size of whatever numTrials are specified to be, we can’t get complex code of the rows to fill as we did before. Thus, we use square brackets to subset the data frame when Pred is equal to PredA or PredB.

Get hands-on with 1400+ tech skills courses.