9.4 Returning Multiple Values

Lists combine many different sorts of objects into one object. This makes them very useful in the context of certain functions.

Consider, for example, the drunken-turtle simulation from Section 6.8:

Suppose that we would like to store several of the results of the simulation:

  • the vector of the number of close returns on each repetition;
  • the table made from the close-returns vector;
  • the mean number of returns.

Unfortunately a function can only return one object.

The solution to your problem is to make a list of the three objects we want, and then return the list. We can re-write the function so as to make all output to the console optional. The function will construct the list and return it invisibly.

Now we can run the function simply to acquire the simulation results for later use:

We can use any of the results at any time and in any way we like:

## On the first ten repetitions, the number of close returns were:
##   0 6 4 4 2 0 2 5 2 4