Functions in R
A function is a block of organized and reusable code that is used to perform a specific task in a program. A function is created by using the function keyword.
The basic syntax of a function is given below:
FunctionName <- function(arg1, arg2, ...) {
Function Body
}
Want to get certified in R! Learn R from top R experts and excel in your career with Intellipaat’s R Programming certification!
where,
- FunctionName is the name of a function that is stored as an R object.
- Arguments are used to provide specific inputs to a function while a function is invoked. A function can have zero, single, multiple, or default arguments.
- Function Body contains the block of code that performs the specific task assigned to a function.
- Return Value is the value that a function returns when it succeeds in performing the task. We can also make a function with no return value.
So now that we have learned what functions in R programming are, let’s have a quick rundown of all the topics that will be covered in this tutorial
R Functions Types
There are two types of functions in R:
- In-built functions
- User-defined functions
In-built Functions
These functions in R programming are provided by the R environment for direct execution, to make our work easier.
Some examples for the frequently used in-built functions are as follows:
#seq() To create a sequence of numbers
print(seq(1,9))
Output:
[1] 1 2 3 4 5 6 7 8 9
#sum() To find the sum of numbers
print(sum(25,50))
Output:
[1] 75
#mean() To find the mean of numbers
print(mean(41:68))
Output: [1] 54.5
#paste() To combine vectors after converting them to characters
paste(1,"sam",2,"rob",3,"max")
Output:
[1] "1 sam 2 rob 3 max"
paste(1,"sam",2,"rob",3,"max", sep = ',') #sep is used to separate the values
We have the perfect professional R Programming Training in Toronto for you!
Output:
[1] "1,sam,2,rob,3,max"
paste(1:3, c("sam","rob","max"), sep = '-', collapse = " and ")
#collapse is used to separate the values when a vector is passed
Output:
[1] "1-sam and 2-rob and 3-max"
#paste0() Has default sep=“” argument
paste0(1,"sam",2,"rob",3,"max")
Output:
[1] "1sam2rob3max"
paste0(1:3, c("sam","rob","max"), collapse = " and ")
Output:
[1] "1sam and 2rob and 3max"
head(x,n) #To retrieve the first n rows of a matrix, data frame, or a vector
x = data frame, matrix, or vector
n = number of rows to be retrieved
empid <- c(1:4)
empname <- c("Sam","Rob","Max","John")
empdept <- c("Sales","Marketing","HR","R & D")
emp.data <- data.frame(empid,empname,empdept)
print(head(emp.data,3))
Output:
empid empname empdept
1 1 Sam Sales
2 2 Rob Marketing
3 3 Max HR
tail(x,n) #To retrieve the last n rows of a matrix, data frame, or a vector
x = data frame, matrix, or vector
n = number of rows to be retrieved
empid <- c(1:4)
empname <- c("Sam","Rob","Max","John")
empdept <- c("Sales","Marketing","HR","R & D")
emp.data <- data.frame(empid,empname,empdept)
print(tail(emp.data,2))
Output:
empid empname empdept
3 3 Max HR
4 4 John R & D
min() To return the minimum value from a vector.
x <- c(3,45,6,7,89,9)print(min(x))
#max() To return the maximum value from a vector
x <- c(3,45,6,7,89,9)
print(max(x))
Output:
[1] 3
[1] 89
#range() To return the minimum and maximum values from a vector
x <- c(3,45,6,7,89,9)
range(x)
x <- c(3,45,-6,7,89,Inf,9)
range(x)
x <- c(3,45,-6,7,NA,89,Inf,9)
range(x)
x<- c(3,45,-6,7,NA,89,Inf,9)
range(x, na.rm = TRUE) To remove NA from the result (na.rm) is used
Output:
[1] 3 89
[1] -6 Inf
[1] NA NA
[1] -6 Inf
#which.min() To return the index of the minimum value from a vector
x <- c(3,45,6,7,89,9)
print(which.min(x))
#which.max() To return the index of the maximum value from a vector
x <- c(3,45,6,7,89,9)
print(which.max(x))
Output:
[1] 1
[1] 5
Wish to crack Big Data job interviews? Intellipaat’s Top R Interview Questions are meant only for you!
User-defined Functions
These functions in R programming language are declared, and defined by a user according to the requirements, to perform a specific task.
For example:
#Create a function to print the sum of squares of numbers in sequence
sum = 0
Function1 <- function(x) {
for(i in 1:x) {
a <- i^2
sum = sum + a
print(sum)
}
}
#Calling a function
Function1(5)
Output:
[1] 1
[1] 5
[1] 14
[1] 30
[1] 55
#Function without an Argument
sum = 0
Function1 <- function() {
for(i in 1:5) {
a <- i^2
sum = sum + a
print(sum)
}
}
#Calling a function
Function1()
Output:
[1] 1
[1] 5
[1] 14
[1] 30
[1] 55
#Create a function to print the sum of squares of three numbers
Function1 <- function(x,y,z) {
sum = x^2 + y^2 + z^2
print(sum)
}
}
#Calling a function
Function1(2,4,6) #Call by position of arguments
Function1(x=3,y=5,z=7) #Call by names of arguments
Output:
[1] 56
[1] 83
Function1 <- function(x=4,y=5,z=6) {
sum = x^2 + y^2 + z^2
print(sum)
}
#Calling a function
Function1() #Calling a function with default arguments
Function1(6,7,8) #Passing new values to replace default arguments
Output:
[1] 77
[1] 149
In this tutorial we learned what functions in R programming are, the basic syntax of functions in R programming, in-built functions and how to use them to make our work easier, the syntax of a user-defined function, and different types of user-defined functions. In the next session, we are going to learn how to read files in R programming.
For the best of career growth, check out Intellipaat’s R Programming training in Hyderabad and get certified!
How to Create a Function in R
A function in R is a block of code that performs a specific task. It takes inputs and produces outputs. To create a function in R, you need to use the function() keyword. The syntax for creating a function is as follows:
function(name, argument1, argument2, ...){
# code
}
The name is the name of the function. The argument1, argument2, and so on are the names of the arguments that the function takes. The code block is the body of the function. The body of the function is executed whenever the function is called.
For example, the following code creates a function called my_function() that takes two arguments:
function(x, y){
z <- x + y
return(z)
}
This function adds two numbers together and returns the result.
To call a function, you use the function name followed by the arguments in parentheses. For example, the following code calls the my_function() function and prints the result:
z <- my_function(1, 2)
print(z)
This code will print the number 3 to the console.
Here is an explanation of the different parts of the function definition:
- The function() keyword tells R that you are defining a function.
- The name is the name of the function. It is a good practice to give functions descriptive names that make it clear what the function does.
- The argument1, argument2, and so on are the names of the arguments that the function takes. Arguments are the inputs to the function.
- The code block is the body of the function. The body of the function is executed whenever the function is called.
- The return() statement returns the output of the function.