Loading, please wait...

A to Z Full Forms and Acronyms

What are the Functions in the R programming language?

Nov 29, 2021 #RLanguage #Programming, 633 Views
In this article, you will understand the R-Functions.

What are the Functions in the R programming language?

Function

The set of statements that performs the definite tasks is known as Function. R programming language has a set of in-built functions. Moreover, the user can create their function also. 

In the R programming language, the functions consider as an object. It helps the R interpreter to pass control to the function along with the arguments that may be required to perform the functional tasks. 

The function helps to reduce the length of the code. It turns the performance and returns control to the interpreter along with the result that is stored in the different object. The function keyword uses to create the function.

The basic syntax of the function is:

Function_name <- function(agr1, arg2, …. , argn)

{

    Body of the function # It has a set of statements that performs the specific task.

Components of the function:

The function has different types of components. Some components are:

  • Function Name: It is the actual name of the function. Whenever the function is called in the program, it calls with the name of the function. It is stored as the object with the name. 
  • Arguments: An argument is optional in the function. The argument is a placeholder for a specific function. When a programmer invokes the function, it passes the value to the argument. It may contain default values too. 
  • Function Body: It contains the set of statements that performs the specific task. 
  • Return Value: It is the last expression in the function.

 

Built-in Functions

Built-in Functions have predefined meanings. The built-in functions are already defined in the packages or libraries of the R environment. There is no need to define the built-in functions. It is used directly in the program. 

Some examples of functions are mean(), max(), sum(y), etc. These functions are directly called by the programmer whenever and wherever needed. 

# Create a sequence of numbers from 32 to 44.

print(seq(23,35))

# Find the sum of numbers from 41 to 68.

print(sum(21:32))

 

OUTPUT

[1] 23 24 25 26 27 28 29 30 31 32 33 34 35

[1] 318

 

User-defined functions

User-defined functions are defined and declared by the user. These functions are not available in any of the packages or libraries.

Example of creating a function

#Function to print number series.

Sequence.function <- function(x) {

   for(i in 1:x) {

      y <- i^2

      print(y)

   }

}

Example of calling function

# Syntax to call a function in which an argument is passed.

Sequence.function(6)

The function can also be called without any arguments.

A to Z Full Forms and Acronyms