Get startedGet started for free

Writing Functions

1. Writing Functions

You now know about different ways to use R functions, but this is not the end. You can also write your own R functions.

2. When write your own?

You might wonder when you would want to do this. Well, this is mostly a question of experience, but there are some guidelines. A function typically serves a particular need or solves a particular problem, without having to care about how the function does this. Remember the 'black-box principle' I mentioned before? If you're writing your own functions, you are writing your own black box that takes inputs and generates an output. How the black box goes about solving its task is not important once you've written the function. You want to be able to use this function just as if it was a standard R function, such as mean(), sd() or list(). You don't know how these work under the hood either, do you?

3. The triple() function

Writing your own functions is super simple as soon as you know the syntax. Let's define a function that calculates the triple of its input, called triple. In a black-box manner, it would look like this: a numeric goes in, the triple function does its magic, and the triple of the numeric comes out.

4. The triple() function

How does this look in R code? You use the function construct for this. This function recipe reads itself as: create a new function, my_fun, that takes arg1 and arg2 as arguments and performs the code in the body on these arguments, eventually generating an output.

5. The triple() function

In our case, we want our function to be called triple, so let's go ahead and take that step. Next, we also know that our triple function will have a single input, a number.

6. The triple() function

We replace the arg1, arg2 part by a single argument, named x. We're almost there. What do we want the body, the function's actual code, to be?

7. The triple() function

To calculate the triple of x, we simply put 3*x.

8. The triple() function

If we execute this function definition, a new object gets defined in our workspace, triple. Now, let's go ahead and calculate the triple of 6. Just like we did before with R's built-in functions, we use standard parentheses. If we call triple(6), R figures out that the x argument corresponds to the value 6. Next, the function's body is executed, calculating 3 times 6. The result is 18. How does R know that it has to return this value? That's because the last expression evaluated in an R function becomes the return value.

9. return()

You can also explicitly specify the return value, by using the return statement. Let's change the function body to use a intermediary value y. Inside the function, we assign to y the triple of x and next, we return this value y. If we source this function, and call the triple function on the variable 6, we get the exact same result, 18. Using a return at the end of your function body is not always useful, but there are other cases where the return statement will come in handy. We'll learn about them in a bit.

10. The math_magic() function

Let's try something different now. Suppose we want to write a function, called math_magic, that takes two numbers as inputs, and calculates the sum of the product and the division of both numbers.

11. The math_magic() function

So if we put in 4 and 2

12. The math_magic() function

we want it to return (4 times 2) plus (4 divided by 2), which is 10.

13. The math_magic() function

Let's start over from our function recipe.

14. The math_magic() function

We replace my_fun by math_magic

15. The math_magic() function

and change the arguments of the function to have two inputs, a and b. By the way, I'm just choosing these two argument names, but you can choose other names as well, as long as they are consistent with the function body

16. The math_magic() function

Finally, we modify the body. We don't need to include a return statement. Sourcing this function and calling it on the numbers 4 and 2 gives us the result we expect. Great! Let's experiment some more. What happens if we call math_magic with only one argument? We get an error because the argument b is missing with no default. We could solve this by making the second argument of the math_magic function optional.

17. Optional argument

We do this by adding default value, say, 1, to the argument list of the function using the equals sign. Sourcing the function definition again and calling math_magic(4) now, gives us 8. Because the b argument was not specified, R set b to 1 inside the function, so 4 times 1 plus 4 divided by 1 was computed, resulting in 8. Let's now call the math_magic function with the numbers 4 and 0. The result is Inf, R's way of saying infinity. That's because R divided 4 by 0 in the second part of the calculation, which leads to infinity. Suppose we want to guard our function against this misuse of the math_magic function, by having the function return 0 when the b argument is 0.

18. Use return()

We can simply extend our function with an if-test with a return statement inside. If we now call the math_magic function with the second argument equal to 0, the condition for the if-test is true and we simply return zero. The return statement, similar to the break statement in a for and while loop, returns 0 and the rest of the function body is ignored. The a times b plus a divided by b part of the function is never reached in this case. Using the return statement, which proves to be quite useful here, we can halt the execution virtually anywhere we want.

19. Let's practice!

I guess those were my 2 cents on writing functions. Time to get your own R functions rolling!

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.