13.3 Return values
13.3.1 Implicit return
As mentioned above, we can return values from a function using return()
. However, if you omit the return()
statement, R will still return something - simply the last statement it evaluates:
> normalize <- function(x){
+ (x - min(x)) / (max(x) - min(x))
+ }
>
> x <- rnorm(5)
> normalize(x)
[1] 0.0000000 0.2443474 1.0000000 0.1218673 0.7942871
Although it is good to know that this feature exists, it is recommended to always explicitely use return()
. The function return()
is the correct tool to clearly designate “leaves” of your code where the routine should end, jump out of the function and a return value. This is also recommended by the Google style guide.
13.3.2 Multiple return statements
Inside a function, you will often encounter conditionals (if
/else
statements) that handle specific cases. Depending on the case, you might want to return something different - i.e. use multiple return()
statements:
13.3.3 Returning multiple values
As we have seen above, return()
only returns a single R object. If you want to return multiple values from a function, you need an R object that stores multiple values. A very convenient object in list()
, as it can store objects of different classes. In addition, you can name these objects, which comes in handy when evaluating the return values of a function. Say we want a function that calculates summary statistics on data, but all in once:
> calculateSummaryStats <- function(x){
+ mean <- mean(x)
+ variance <- var(x)
+ stddev <- sd(x)
+ allInOne <- list(mean = mean, variance = variance, stddev = stddev)
+ return (allInOne)
+ }
We calculate mean, variance and standard deviation of our data, bind the results to a list and return the list. We can now extract the results easily:
13.3.4 Exercises: Return Values
See Section 18.0.34 for solutions.
Program the factorial function with a for loop.
Program the factorial function using the function
prod()
.Write a function to simulate rolling a dice 100 times and to count the number of 6’s (use a loop). Return both the simulated numbers and the total number of 6’s.
Again write a function to simulate rolling a dice 100 times and to count the number of 6’s. But now, use as few instructions as possible. Can you try to avoid using a loop?
Implement a fizzbuzz function. It takes a single number as input. If the number is divisible by three, it returns “fizz”. If it’s divisible by five it returns “buzz”. If it’s divisible by three and five, it returns “fizzbuzz”. Otherwise, it returns the number. Make sure you first write working code before you create the function.