Functions in R Programming

Filed Under: R Programming

A function in programming is a reusable chunk of code that performs a certain job. For example, if you need to calculate an average of a list of values multiple times, it would be tedious to keep adding code for the operation each time. Instead, you could write a function that calculates the average and call it as many times as you want.

R has hundreds of built-in functions that perform mathematical and graphical operations. R also allows you to define your own customized functions to suit your needs. This tutorial aims to help you with rules in writing and calling functions in R.

Components of an R Function

The functions in R can be specified by a function keyword. The following is the syntax for writing functions in R.

functionname <- function(argument1, argument2...){
# What you want the function to do
return(returnobject)}
  • The function name here can be any valid R identifier like we discussed earlier.
  • Arguments are the values that we wish to pass to the function. A function may or may not take any arguments.
  • The function manipulates these arguments within its body. The body is the code enclosed between the braces.
  • The return statement at the end of the function is used to return the value computed by the function. This can be a numeric value or an object that is created or manipulated within the function body.

A simple R function example

Let’s now write a simple function to understand how this works.

myname <- function(name){
  paste("Hello",name)
} 
name <- readline()
myname(name)

Before we proceed, paste() is a built-in function that concatenates and prints two strings.

We have created a function named myname above, which takes a single argument called name. In the function’s body, it prints a message “Hello + name”.

The name is taken from user input using another built-in function readline(), which can read an entire line with spaces until a newline character is encountered.

Finally, we are calling the function with the name argument. Let us see how the output goes.

Output:

> name <- readline()
Neil Armstrong
> myname(name)
[1] "Hello Neil Armstrong"

After we compile the function block using ctrl + enter, a new section named functions is created in the environment and the function myname is registered there.

As we give the value “Neil Armstrong” to the name variable through our standard input (keyboard), the value gets passed into the function and finally the intended message “Hello Neil Armstrong” is displayed on the console.

Writing R functions with a return value

Now let us try out another function and see how the return statement works. Consider a function that takes two numbers, computes the average and returns the average value.

average <-function(num1,num2){
  return((num1+num2)/2)
}

This function returns a computed value which can be accessed in the calling statement. The return value is stored in the variable c here.

a=4
b=5
c=average(a,b)
print(c)

Output:

[1] 4.5

Argument handling in R

R incorporates lazy evaluation in function handling. This means that expressions are evaluated only when needed.

R also supports giving default values to arguments.

myname2 <- function(name="no name"){
  paste("Hello",name)
}

myname2()

Similar to the above myname function, we have written a myname2 function, but we have a default argument for the name variable with value “no name“. Let us see what happens when we call the function without an argument.

> myname2()
[1] "Hello no name"
> myname2("JournalDev")
[1] "Hello JournalDev"

Without any argument, the function displays the default argument.

R also facilitates checking of missing arguments in functions using missing keyword. This is illustrated using an example below.

We would like to display a message stating that one of the arguments is missing in the function when only one number is supplied.

#Display an error message when either of the arguments is missing and return #NULL
average <-function(num1,num2){
  if(missing(num1)|missing(num2)){
    print("needs two arguments for average")
    return(NULL)
  }
  return((num1+num2)/2)
}

Now we call average() using a single argument.

average(2)

Output:

> average(2)
[1] "needs two arguments for average"
NULL

This will prove a useful feature when writing complex functions further.

Variable Arguments in R Function

R also allows variable-length arguments list for functions. You can pass arguments without first defining them in the argument list. This is done by using an ellipsis or three dots (...). For example, a function can be defined as follows.

#Ellipsis represents any number of arguments.
elfunction <-function(...){
  args <- list(...)
  sum <- as.integer(0)
  for(i in 1:length(args)){
    sum=sum+as.integer(args[i]) 
  }
  print(sum)
}

Ignore the structure of for loop for now, just keep in mind that it iterated over the entire length of the arguments list to cumulatively add to the sum value which is initially set to 0. Let us check the output for different cases.

> elfunction(1,2,3,4,5)
[1] 15
> elfunction(8,6,24)
[1] 38
> elfunction(1,1,1,1,1,1,1,1,1,1,1,1,1) 
[1] 13

Observe how the elfunction we defined takes any number of arguments without having to define a new one for each. This is a very flexible feature in R.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages