User-Defined Functions in R Programming with Examples

Functions in a programming language are sets of instructions. They divide the code into logical chunks. They help to reduce the complexity of the program and to avoid repetition.

In this article, we are going to learn how to create user-defined functions in R. We will see when they are needed and what we can do with them. Are you ready for some learning?

What is R function?

A function is a collection of instructions or statements that work together to accomplish a definite task. R treats functions as objects. The interpreter can pass control to them along with the arguments required by the function. Once the function has achieved its objective, it passes control back to the interpreter.

Components of R function

The following are the components of any function in R. A function may or may not have all or some of them.

  1. Function name: Every function needs a name. This name is used to call the function from other parts of the program. R stores a function as an object with this name given to it.
  2. Arguments: Arguments are placeholders for the inputs a function may require. When we call a function, we need to provide the proper values for all the arguments the function needs. A function may or may not have one or more arguments.
  3. Function body: A function’s body contains a set of instructions or statements. The body is where the magic happens. A function completes its task by running the code inside its body.
  4. Return value: After the function has completed its task, it may or may not return a value before handing over control to the interpreter. This return value can be the result of the task done by the function or confirmation about the completion or failure of the task.

Follow TechVidvan on Google & Stay updated with latest technology trends

Syntax of function

The following is the syntax for a user-defined function in R:

Function_name <- function(arguments){
   function_body
   return (return)
}

Where function_name is the name of the function,
arguments are the input arguments needed by the function,
function_body is the body of the function,
return is the return value of the function.

How to call R function?

Once you have created a function, how do you call it? Where can you call the function?

You can call a function from anywhere in the environment in which the function is declared. We will read more about global and local environments and scopes in a later section.

To call a function, we simply have to use the function’s name and provide appropriate arguments. For example:

function_name(arguments)

Where function_name is the name of the function you want to call,

and arguments are the arguments needed by the function.

If the function doesn’t need any arguments, the parenthesis can be left empty.

When do you need the R function?

As a general rule of thumb, we would say you need a function if you need to run the same few lines of code more than once. Look at the example below:

Code:

vec1 <- c(28,64,63,43,56,46,87,34,73)
vec2 <- c(53,37,29,45,68,33,76,49,30)
vec3 <- c(12,44,36,75,36,93,34,64,18)
vec1 <- ((vec1-min(vec1))/(max(vec1)-min(vec1)))
vec2 <- ((vec2-min(vec2))/(max(vec2)-min(vec2)))
vec3 <- ((vec3-min(vec3))/(max(vec3)-min(vec3)))
vec1

Code:

vec2
vec3

Output:

when need functions in R

The above code rescales the vectors to a range of 0 to 1. The formula for that is reused every time. This approach is time-consuming and prone to errors. Instead, if we can define a function that does the calculation on an input vector, our work would become much easier and faster.

Code:

rescale <- function(vec){
  vec <- ((vec-min(vec))/(max(vec)-min(vec)))
  return(vec)
}
rescale(vec1)

Code:

rescale(vec2)
rescale(vec3)

Output:

when need R function rescale()

Forgot how to use R vectors? Revise vectors in R

Single line functions

The curly brackets around the function’s body are not necessary if the body consists of a single line of code only. For example:

Code:

vec1 <- c(28,64,63,43,56,46,87,34,73)
reciprocal <- function(vec) vec <- 1/vec
rvec1 <- reciprocal(vec1)
rvec1

Output:

single line R functions

Return value

Sometimes, we need the functions to return the results of their processing. For example, the following function returns a string telling whether or not the input number is divisible by three.

Code:

check <- function(x){
  if(x%%3==0){
    result <- "the number is divisible by three"
  }else {
    result = "the number is not divisible by three"
  }
  return(result)
}

Here are a few test runs of the function:

Code:

check(6)
check(12)
check(11)
check(8)

Output:

return value divisible 3 - functions in r

In case the return statement is not present, R returns the value of the last expression in the function by default.

Code:

check <- function(x){
  if(x%%3==0){
    result <- "the number is divisible by three"
  }else {
    result = "the number is not divisible by three"
  }
  result
}

Code:

check(17)

Output:

return value divisible 3 default - functions in r

Explore if-else and other control structures in R

Scope of R functions

An environment is the collection of all the variables and objects. The top-level of the environment is the global environment. When we create a function, it creates a local environment that exists in the global environment. The function operates inside the local environment.

Local vs global variables

Global variables are variables declared in a global scope that is they are accessible from anywhere in the global environment.

Local variables are variables declared in a local scope i.e. they are only accessible inside their local environment.

Note: Global variables are accessible inside local environments but local variables are not accessible outside their local environments.

Variables and objects created inside a function, exist only inside the function’s local environment. If an object does not exist inside the function’s local environment, then the interpreter tries to find it in the global environment.

Recursive functions

It is possible for functions to call themselves. We call a function that calls itself, a recursive function. We call this technique, recursion.

Recursion is useful to break down larger repetitive problems into smaller chunks. Take a look at the following factorial function.

Code:

factorial <- function(x){
  if(x==0)
    return(1)
  else
    return(x*factorial(x-1))
}

factorial(5)

Code:

factorial(11)

Output:

recursive R functions

Summary

Functions are the basic building blocks of complex programs. They help in keeping the code organized and short. They also help in increasing the accuracy of the code. Breaking down code in functions is the easiest way to organize and improve the program.

In this R functions tutorial, we learned about functions and their use. We saw how they are created and a few of their weird quirks. We also learned about their scope and environments. Finally, we looked at recursive functions.

We at TechVidvan hoped that you understand the basics of functions in R. After reading this tutorial, you should be able to write your own customized functions.

If you find any difficulty while practicing R functions, ask your doubts from TechVidvan Experts in the comment section.

Keep Learning ?

Did we exceed your expectations?
If Yes, share your valuable feedback on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *