Creating Functions in R

In the previous lesson, we learned about how to use functions in R. This is very useful because R has a lot of built-in functions which we can use to make coding easy. The beauty of functions is that we can just use them in our programs without knowing anything about their inner workings.

Remember the sd() function? We just used it in our program to calculate the standard deviation. Inside of it, it is actually a detailed program which calculates the standard deviation. However, since we are just users of the function, we simply use it and don't have to know anything about what's happening inside of it. Another important thing about functions is that we can use them multiple times in our code and because they abstract away functionality, they make our programs short, clean and error-free.

The good thing is that in R we can write our own functions. This can be useful when we know that we will be using a custom piece of functionality multiple times in our programs.

Functions are created using the function() directive and are stored as R objects just like anything else. In particular, they are R objects of class "function".

f <- function(<arguments>) {
  ## Do something interesting
}

Functions in R are “first class objects”, which means that they can be treated much like any other R object. Importantly,

  • Functions can be passed as arguments to other functions
  • Functions can be nested, so that you can define a function inside of another function

The return value of a function is the last expression in the function body to be evaluated.

Example: DoubleIt Function

This content is for paid members only.

Join our membership for lifelong unlimited access to all our data science learning content and resources.