Functions in R
In R, a function is defined as a set of statements which are organized together to perform a specific task.
R provides various built-in functions, and it allows the user to define their own functions (user-defined functions).
Built-in functions:
R provides various built-in functions, some of them are,
print()cat()readline()scan()class()sprintf()paste()c()list()matrix()array()abs()sqrt()floor()ceiling()round()min()max()mean()sum()as.numeric()as.character()as.logical()as.integer()
User-defined functions:
R enables us to create our own functions; these functions are known as user-defined functions.
- In R, the function is created using a keyword called function.
Syntax:
func_name <- function(arg_1, arg_2, ...) {
Function body
}
- To call a function, use the function name followed by parenthesis, like func_name().
Example:
R program to create a simple function.Filename: sampleFun.R
# function creation
sample_fun <- function() {
print("This is Sample Function")
}
# function calling
sample_fun()
Output: $ Rscript sampleFun.R
[1] "This is Sample Function"
Parameters or Arguments in R Functions:
Parameters or arguments are used to pass the information (values) to the function. These are optional. A function can have any number of arguments, they are separated by comma in parentheses.
Example:
R program to create a function with two arguments/parameters.Filename: addFunction.R
# function to add 2 numbers
add_nums <- function(x, y) {
result <- x + y
print(result)
}
add_nums(25, 36) # calling add_nums function
Output: $ Rscript addFunction.R
[1] 61
Default Value of Parameter:
R allows us to use default values for the parameters in user defined functions. These values are used by functions if user doesn’t pass any parameter value while calling a function.
Example:
R program to create a function with default parameter values.Filename: defaultFunction.R
# function definition with default values
area_Rect = function(length = 4, width = 3) {
area = length * width
print(area)
}
# function calling with arguments
area_Rect(6, 3)
# function calling with arguments by changing order
area_Rect(width = 6, length = 5)
# function calling without arguments
area_Rect()
Output: $ Rscript defaultFunction.R
[1] 18
[1] 30
[1] 12
Return Value (or) return function:
You can use return() function if you want your function to return the result.
Example:
R program to create a function with return() function.Filename: returnFunction.R
# function definition with return
sqr_fun = function(x) {
result = x * x
return(result) # return the result
}
# function calling
print(sqr_fun(6))
Output: $ Rscript returnFunction.R
[1] 36
Recursive Function:
R also supports function recursion, which means that a function can call 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.
Example:
R program to find the factorial of the given number using recursive function.Filename: factorial_fun.R
# function definition
factorial_fun <- function(x) {
if (x == 0 || x == 1) {
return(1)
} else {
return(x * factorial_fun(x - 1))
}
}
# function calling
print(factorial_fun(5))
Output: $ Rscript factorial_fun.R
[1] 120
Global Variables:
Variables that are created outside of a function are known as global variables. Global variables can be used by everyone, both inside of functions and outside.
Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.
- To create a global variable inside a function, you can use the global assignment (<<-) operator.
Example:
R program to create a global variable.Filename: globalVar.R
# function definition
my_fun <- function() {
# global variable
msg <<- "Programming Language"
print(paste("R is", msg))
}
my_fun() # function calling
print(msg) # print global variable
Output: $ Rscript globalVar.R
[1] "R is Programming Language"
[1] "Programming Language"
- Also, use the global assignment operator if you want to change a global variable inside a function.
Example:
R program to change the value of a global variable.Filename: globalvarVal.R
msg <- "Programming Language"
# function definition
my_fun <- function() {
# changing value of global variable
msg <<- "Scripting Language"
print(paste("R is", msg))
}
my_fun() # function calling
print(msg) # print global variable
Output: $ Rscript globalvarVal.R
[1] "R is Scripting Language"
[1] "Scripting Language"