Get startedGet started for free

Returning values from functions

1. Returning values from functions

As you've seen, the value that is returned from a function is the last value that was calculated when the end of the function body was reached. Sometimes however, it's useful to return early.

2. A simple sum function

Consider this simple version of sum. You take a numeric vector, x, and loop over its values adding each element. If any of the values in x is NA, then the result will also be NA, so there isn't any point in adding numbers together. Let's add a check for missing values at the start of the function using anyNA. If that condition holds, we want to tell the function to return the value NA. This is done using the return function. You pass the value you want to return, and it exits simple_sum early.

3. Geometrics means again

Here's the geometric mean function from the previous video. When x has non-positive values, it throws an error. This is possibly too harsh an outcome.

4. Returning NaN with a warning

Instead, you could give a warning that there was a problem, then return not-a-number. This mimics what happens when you call log with a negative number.

5. Reasons for returning early

To summarize, there are two reasons for returning early. Either you know the answer before completing all the calculations, or the input is an edge case -- that is, it's weird, but not weird enough to throw an error.

6. Hiding the return value

Here's the simple sum function again. If you call it without assigning the result, it will print the answer in the console.

7. Hiding the return value

You can prevent the return value from being printed by wrapping it in a call to invisible. This isn't so useful for functions that calculate things, but it is useful for functions that generate output.

8. Many plots invisibly return things

For example, all ggplots, and some base R plots will invisibly return a value. That means they don't print any output in the console. Consider this histogram of visits to Snake River. The result isn't assigned to anything, but you don't see the details of the ggplot object in the console. Instead, the code just draws a plot.

9. Many plots invisibly return things

Let's change the code to assign the result. Now, if you call str on the result, you can see that it's an object of class gg that was invisibly returned.

10. Let's practice!

Time to return to the coding exercises.

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.