The Wayback Machine - https://web.archive.org/web/20241126174547/https://www.geeksforgeeks.org/functions-in-r-programming/
Open In App

Functions in R Programming

Last Updated : 11 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A function accepts input arguments and produces the output by executing valid R commands that are inside the function.

Functions are useful when you want to perform a certain task multiple times.

In R Programming Language when you are creating a function the function name and the file in which you are creating the function need not be the same and you can have one or more functions in R.

Creating a Function in R Programming

Functions are created in R by using the command function(). The general structure of the function file is as follows: 

Functions in R Programming-Geeksforgeeks

Functions in R Programming

Note: In the above syntax f is the function name, this means that you are creating a function with name f which takes certain arguments and executes the following statements.

Parameters or Arguments in R Functions:

Parameters and arguments are same term in functions.

Parameters or arguments are the values passed into a function.

A function can have any number of arguments, they are separated by comma in paranthesis.

Example:

R




# function to add 2 numbers
add_num <- function(a,b)
{
  sum_result <- a+b
  return(sum_result)
  }
# calling add_num function
 sum = add_num(35,34)
#printing result
print(sum)


Output

[1] 69

No. of Parameters:

Function should be called with right no. of parameters, neither less nor more or else it will give error.

Default Value of Parameter:

Some functions have default values, and you can also give default value in your user-defined functions. These values are used by functions if user doesn’t pass any parameter value while calling a function.

Return Value:

You can use return() function if you want your function to return the result.

Read More: R Function Parameters

Calling a Function in R

After creating a Function, you have to call the function to use it.

Calling a function in R is very easy, you can call a function by writing it’s name and passing possible parameters value.

Passing Arguments to Functions in R Programming Language

There are several ways you can pass the arguments to the function: 

  • Case 1: Generally in R, the arguments are passed to the function in the same order as in the function definition.
  • Case 2: If you do not want to follow any order what you can do is you can pass the arguments using the names of the arguments in any order.
  • Case 3: If the arguments are not passed the default values are used to execute the function.

Now, let us see the examples for each of these cases in the following R code:

R




# A simple R program to demonstrate
# passing arguments to a function
 
Rectangle = function(length=5, width=4){
  area = length * width
  return(area)
}
 
# Case 1:
print(Rectangle(2, 3))
 
# Case 2:
print(Rectangle(width = 8, length = 4))
 
# Case 3:
print(Rectangle())


Output

[1] 6
[1] 32
[1] 20

Types of Function in R Language

  1. Built-in Function: Built-in functions in R are pre-defined functions that are available in R programming languages to perform common tasks or operations.
  2. User-defined Function: R language allow us to write our own function.   

Built-in Function in R Programming Language

Built-in Function are the functions that are already existing in R language and you just need to call them to use.

Here we will use built-in functions like sum(), max() and min().

R




# Find sum of numbers 4 to 6.
print(sum(4:6))
 
# Find max of numbers 4 and 6.
print(max(4:6))
 
# Find min of numbers 4 and 6.
print(min(4:6))


Output

[1] 15
[1] 6
[1] 4

Other Built-in Functions in R:

Let’s look at the list of built-in R functions and their uses:

Functions

Syntax

 Mathematical Functions  

abs()

calculates a number’s absolute value.

sqrt()

calculates a number’s square root. 

  round()

rounds a number to the nearest integer.

exp()

calculates a number’s exponential value

log()

which calculates a number’s natural logarithm.

cos(), sin(), and tan()

calculates a number’s cosine, sine, and tang.
Statistical Functions  

mean()

 A vector’s arithmetic mean is determined by the mean() function. 

median()

 A vector’s median value is determined by the median() function.

cor()

calculates the correlation between two vectors.

var()

 calculates the variance of a vector and calculates the standard deviation of a vector.
Data Manipulation Functions  

unique()

 returns the unique values in a vector.

subset()

subsets a data frame based on conditions.

aggregate()

 groups data according to a grouping variable.

order()

uses ascending or descending order to sort a vector.
File Input/Output Functions  

read.csv()

reads information from a CSV file. 

Write.csv()

publishes information to write a CSV file.

Read. table()

reads information from a tabular.

Write.table()

 creates a tabular file with data.

User-defined Functions in R Programming Language

User-defined functions are the functions that are created by the user.

User defines the working, parameters, default parameter, etc. of that user-defined function. They can be only used in that specific code.

Example  

R




# A simple R function to check
# whether x is even or odd
 
evenOdd = function(x){
  if(x %% 2 == 0)
    return("even")
  else
    return("odd")
}
 
print(evenOdd(4))
print(evenOdd(3))


Output 

[1] "even"
[1] "odd"

R Function Examples

Now let’s look at some use cases of functions in R with some examples.

1. Single Input Single Output

Now create a function in R that will take a single input and gives us a single output. 

Following is an example to create a function that calculates the area of a circle which takes in the arguments the radius. So, to create a function, name the function as “areaOfCircle” and the arguments that are needed to be passed are the “radius” of the circle.  

R




# A simple R function to calculate
# area of a circle
 
areaOfCircle = function(radius){
  area = pi*radius^2
  return(area)
}
 
print(areaOfCircle(2))


Output

[1] 12.56637

2. Multiple Input Multiple Output

Now create a function in R Language that will take multiple inputs and gives us multiple outputs using a list. 

The functions in R Language take multiple input objects but returned only one object as output, this is, however, not a limitation because you can create lists of all the outputs which you want to create and once the list is created you can access them into the elements of the list and get the answers which you want.

Let us consider this example to create a function “Rectangle” which takes “length” and “width” of the rectangle and returns area and perimeter of that rectangle. Since R Language can return only one object. Hence, create one object which is a list that contains “area” and “perimeter” and return the list. 

R




# A simple R function to calculate
# area and perimeter of a rectangle
 
Rectangle = function(length, width){
  area = length * width
  perimeter = 2 * (length + width)
   
  # create an object called result which is
  # a list of area and perimeter
  result = list("Area" = area, "Perimeter" = perimeter)
  return(result)
}
 
resultList = Rectangle(2, 3)
print(resultList["Area"])
print(resultList["Perimeter"])


Output

$Area
[1] 6

$Perimeter
[1] 10


3. Inline Functions in R Programming Language

Sometimes creating an R script file, loading it, executing it is a lot of work when you want to just create a very small function. So, what we can do in this kind of situation is an inline function.

To create an inline function you have to use the function command with the argument x and then the expression of the function. 

Example

R




# A simple R program to
# demonstrate the inline function
 
f = function(x) x^2*4+x/3
 
print(f(4))
print(f(-2))
print(0)


Output

[1] 65.33333
[1] 15.33333
[1] 0

Lazy Evaluations of Functions in R Programming Language

In R the functions are executed in a lazy fashion. When we say lazy what it means is if some arguments are missing the function is still executed as long as the execution does not involve those arguments.

Example

In the function “Cylinder” given below. There are defined three-argument “diameter”, “length” and “radius” in the function and the volume calculation does not involve this argument “radius” in this calculation. Now, when you pass this argument “diameter” and “length” even though you are not passing this “radius” the function will still execute because this radius is not used in the calculations inside the function. 
Let’s illustrate this in an R code given below:

R




# A simple R program to demonstrate
# Lazy evaluations of functions
 
Cylinder = function(diameter, length, radius ){
  volume = pi*diameter^2*length/4
  return(volume)
}
 
# This'll execute because this
# radius is not used in the
# calculations inside the function.
print(Cylinder(5, 10))


Output

[1] 196.3495

If you do not pass the argument and then use it in the definition of the function it will throw an error that this “radius” is not passed and it is being used in the function definition.

Example

R




# A simple R program to demonstrate
# Lazy evaluations of functions
 
Cylinder = function(diameter, length, radius ){
  volume = pi*diameter^2*length/4
  print(radius)
  return(volume)
}
 
# This'll throw an error
print(Cylinder(5, 10))


Output 

Error in print(radius) : argument "radius" is missing, with no default

We have discussed all about R functions to give you some idea about using functions in R language. You can go and study each individual in-built function on this page to completely grasp the concept of R functions and their uses.

Also Check:



Previous Article
Next Article

Similar Reads

Recursive Functions in R Programming
Recursion, in the simplest terms, is a type of looping technique. It exploits the basic working of functions in R. Recursive Function in R: Recursion is when the function calls itself. This forms a loop, where every time the function is called, it calls itself again and again and this technique is known as recursion. Since the loops increase the me
4 min read
Logarithmic and Power Functions in R Programming
Logarithm and Power are two very important mathematical functions that help in the calculation of data that is growing exponentially with time. First is the Logarithm, to which the general way to calculate the logarithm of the value in the base is with the log() function which takes two arguments as value and base, by default it computes the natura
3 min read
Conversion Functions in R Programming
Sometimes to analyze data using R, we need to convert data into another data type. As we know R has the following data types Numeric, Integer, Logical, Character, etc. similarly R has various conversion functions that are used to convert the data type. In R, Conversion Function are of two types: Conversion Functions for Data Types Conversion Functi
4 min read
Poisson Functions in R Programming
The Poisson distribution represents the probability of a provided number of cases happening in a set period of space or time if these cases happen with an identified constant mean rate (free of the period since the ultimate event). Poisson distribution has been named after Siméon Denis Poisson(French Mathematician). Many probability distributions c
3 min read
Applying User-defined Functions on Factor Levels of Dataset in R Programming - by() Function
by() function in R programming is an object-oriented wrapper function which performs the provided function on factor levels of the data set passed in the arguments of function call. Syntax: by(data, INDICES, FUN) Parameters: data: represents the dataset INDICES: represents the factor list of dataset FUN: represents the function to be performed on f
1 min read
Performing Logarithmic Computations in R Programming - log(), log10(), log1p(), and log2() Functions
log() function in R Language returns the natural logarithm (base-e logarithm) of the argument passed in the parameter. Syntax: log(x) Parameter: x: Specified value. Returns: It returns the natural logarithm of the specified value, infinity for 0 and NaN for the negative value. Example 1: # R program to calculate log value print(log(1)) print(log(30
3 min read
Get Summary of Results produced by Functions in R Programming - summary() Function
summary() function in R Language is a generic function used to produce result summaries of the results of various model fitting functions. Syntax: summary(object, maxsum) Parameters: object: R object maxsum: integer value which indicates how many levels should be shown for factors Example 1: # R program to illustrate # summary function # Initializi
2 min read
Compute the Parallel Minima and Maxima between Vectors in R Programming - pmin() and pmax() Functions
pmin() function in R Language is used to return the parallel minima of the input vectors. Syntax: pmin(x1, x2) Parameters: x1: vector one x2: vector two Example 1: # R program to illustrate # pmin() function # First example vector x1 <- c(2, 9, 5, 7, 1, 8) # Second example vector x2 <- c(0, 7, 2, 3, 9, 6) # Application of pmin() in R pmin(x1,
1 min read
Compute Beta Distribution in R Programming - dbeta(), pbeta(), qbeta(), and rbeta() Functions
Beta Distribution in R Language is defined as property which represents the possible values of probability. This article is an illustration of dbeta, pbeta, qbeta, and rbeta functions of Beta Distribution. dbeta() Function It is defined as Beta Density function and is used to create beta density value corresponding to the vector of quantiles. Synta
2 min read
Types of Functions in R Programming
A function is a set of statements orchestrated together to perform a specific operation. A function is an object so the interpreter is able to pass control to the function, along with arguments that may be necessary for the function to accomplish the actions. The function in turn performs the task and returns control to the interpreter as well as a
6 min read
Exponential Distribution in R Programming - dexp(), pexp(), qexp(), and rexp() Functions
The exponential distribution in R Language is the probability distribution of the time between events in a Poisson point process, i.e., a process in which events occur continuously and independently at a constant average rate. It is a particular case of the gamma distribution. In R Programming Language, there are 4 built-in functions to generate ex
2 min read
Gamma Distribution in R Programming - dgamma(), pgamma(), qgamma(), and rgamma() Functions
The Gamma distribution in R Programming Language is defined as a two-parameter family of continuous probability distributions which is used in exponential distribution, Erlang distribution, and chi-squared distribution. This article is about the implementation of functions of the gamma distribution. dgamma() Function The dgamma() function is used t
2 min read
Poisson Functions in R Programming
The Poisson distribution represents the probability of a provided number of cases happening in a set period of space or time if these cases happen with an identified constant mean rate (free of the period since the ultimate event). Poisson distribution has been named after Siméon Denis Poisson(French Mathematician). Many probability distributions c
3 min read
What is the Relation Between R Programming and Hadoop Programming?
The relation between R programming and Hadoop revolves around integrating R with the Hadoop ecosystem to analyze large datasets that are stored in a Hadoop environment. R, primarily used for statistical analysis and data visualization, is not inherently built for handling big data. However, when combined with Hadoop, it can leverage Hadoop's distri
3 min read
Union() & union_all() functions in Dplyr package in R
In this article, we will discuss union() and union_all() functions using Dplyr package in the R programming language. Dataframes in use: Example: R program to create data frames with college student data and display them C/C++ Code # create dataframe1 with college # 1 data data1=data.frame(id=c(1,2,3,4,5), name=c('sravan','ojaswi','bobby', 'gnanesh
2 min read
Specify Multiple Arguments in apply Functions in R
In this article, we will discuss how to specify multiple arguments in apply functions in the R programming language. apply() function is used to apply conditions to get the resultant data like mean of data, the sum of data, etc. Syntax: apply(data, margin, function, na.rm = TRUE) where, data is the input dataframemargin is used to specify the width
2 min read
Interpolation Functions in R
In this article, we will be looking towards the approx() and the aproxfun() interpolation function with working examples in the R Programming language. Approx() and Approxfun() interpolation function These functions return a list of points that linearly interpolates given data points, or a function performing the linear (or constant) interpolation.
5 min read
as.double() and is.double() Functions in R
In this article, we will discuss about as.double() and is.double() functions in R Programming Language. as.double() Method in R as.double is used to convert an integer to double. Syntax: as.double(input_values) Both will take values as input. Example: In this example, we will a vector with 5 elements and convert to double using as.double() C/C++ Co
1 min read
cumall(), cumany() & cummean() R Functions of dplyr Package
In this article, we will discuss about cumall(), cummany(), and cummean() functions in R Programming Language. Which are available in dplyr() package. We have to install and load dplyr package. Install - install.packages("dplyr") Load - library("dplyr")cumall() This function will check whether the first element is TRUE. if yes, then it will return
3 min read
apropos() and find() Functions in R?
In this article, we will be discussing the aprops() and the find() functions with these working examples in the R programming language. Functions definitions:apropos() function: This function returns a character vector giving the names of objects in the search list matching what.find() function: This returns where objects of a given name can be fou
2 min read
Model predictions to find the best model fit using the juice() and bake() functions in R
The juice() function in R Programming Language is used to extract the data from a recipe object. It is a part of the recipes package. juice() FunctionA recipe object is a data structure that represents a pre-processing pipeline. It can be used to transform data in a consistent way. The juice() function can be used to extract the data from a recipe
11 min read
Apply a Function (or functions) across Multiple Columns using dplyr in R
Data processing and manipulation are one of the core tasks in data science and machine learning. R Programming Language is one of the widely used programming languages for data science, and dplyr package is one of the most popular packages in R for data manipulation. In this article, we will learn how to apply a function (or functions) across multi
10 min read
How to Handle Invalid Argument Error in R Functions
Handling invalid argument errors in R functions involves implementing proper input validation and providing informative error messages to users. In this guide, we'll explore common practices for handling invalid argument errors, along with examples in R Programming Language. Types of errors for Invalid Argument Error in R FunctionsMissing Argument
3 min read
saveRDS() and readRDS() Functions in R
The saveRDS function is a serialization interface for single objects and it is usually used with the readRDS function. Both saveRDS and readRDS are used for saving individual R Programming Language objects to a connection usually called a file and to restore these objects under different names. saveRDS() and readRDS() Functions in RAll the interfac
7 min read
Aggregate data using custom functions using R
In this article, we will explore various methods to aggregate data using custom functions by using the R Programming Language. What is a custom function?Custom functions are an essential part of R programming, which allows users to create reusable blocks of code tailored to their specific needs. These functions encapsulate a series of operations, m
5 min read
Tidyverse Functions in R
Tidyverse is a collection of R packages designed to make data analysis easier, more intuitive, and efficient. Among the various packages within Tidyverse, several key functions stand out for their versatility and usefulness in data manipulation tasks. In this article, we'll explore some of the most essential Tidyverse functions in R Programming Lan
4 min read
Sorting, Ordering, and Ranking: Unraveling R’s Powerful Functions
R Programming Language is widely used by data scientists and analysts. This language provides various packages and libraries that are user-friendly making analysis easier. The rich set of functions this language provides helps in data manipulation and transformation. In this article, we will understand R's powerful functions and its uses. Differenc
13 min read
How to plot user-defined functions in R?
Plotting user-defined functions in R is a common task for visualizing mathematical functions, statistical models, or custom data transformations. This article provides a comprehensive guide on how to plot user-defined functions in R, including creating simple plots, enhancing them with additional features, and customizing their appearance. Overview
3 min read
How to use data.table within functions and loops in R?
data. table is the R package that can provide the enhanced version of the data. frame for the fast aggregation, fast ordered joins, fast add/modify/delete of the columns by the reference, and fast file reading. It can be designed to provide a high-performance version of the base R's data. frame with syntax and features that are optimized for large
3 min read
Getting the Modulus of the Determinant of a Matrix in R Programming - determinant() Function
determinant() function in R Language is a generic function that returns separately the modulus of the determinant, optionally on the logarithm scale, and the sign of the determinant. Syntax: determinant(x, logarithm = TRUE, ...) Parameters: x: matrix logarithm: if TRUE (default) return the logarithm of the modulus of the determinant Example 1: # R
2 min read
Article Tags :
three90RightbarBannerImg