R Functions

In programming, a function is a group of instructions that you want to use repeatedly, because of their complexity, are better self-contained in sub-program and called when needed. Hence, we can say that a function is a set of code written to perform a specific task; it cannot or can accept arguments or parameters and it cannot or can return one or more values.

In R programming language, a function is an object, so the R interpreter is able to pass control to the function, along with the arguments that may be important for the function to accomplish the actions.

R provides a large number of in-built functions and the user can create their own functions.

Syntax for Function Definition

function_name <- function(arguments) {
# Function body
  return (object)
}

Here,

function_name is the name of the function. In R environment it is stored as an object with this name.

function is a reserved keyword used to declare a function.

arguments is the number of values you can pass in a function. This is optional.

Function body defines within the curly braces which contain a number of statements. These braces are optional if the body contains only a single statement.

Return value is the last expression in the body of the function to be evaluated.

Built-in Functions

We can categorize the built in functions into following groups:

1. Numeric Function

Function

Description

Example

abs(x)

Returns the absolute value of x

a <- abs(x)

sqrt(x)

Returns the Square root of x

a <- sqrt(33.45)

log(x)

Returns the natural log of x

a <- log(200)

exp(x)

Returns the exponential of x

a <- exp(10)

sin(x), cos(x), tan(x)

Returns sine, cosine, or tangent of a value

a <- sin(x)

round(x, digits =n)

Rounding of number

Round(3.475, digits =2) is 3.48

floor(x)

Rounding of number

floor(1.475) is 1


2. Statistical Functions

Function

Description

Example

mean(x)

Returns the mean or average of a set of numbers

y <- c(20, 30, 22)

result.mean <- mean(y)

median(x)

Median of x

result.median <- median(y)

mode

Returns the mode of a range

result.mode <- mode(y)

sd(y)

Shows the standard deviation of range

print(sd(y))

range(y)

Returns the range of values

print(range(y))

pnorm(y)

Shows the normal probability of a number

pnorm(2.334)

sum(x)

Returns the sum of a range

sum(y)

min(x)

Returns the minimum of a range

min(y)

max(x)

Returns the maximum of a range

max(y)


3. Character Functions

Function

Description

Example

subtstr(x, start =n1, stop =n2)

Extract or replace substrings in a character vector

substr(“abcdef”, 2, 4)

grep(pattern, x, ignore.case = FALSE, fixed = FALSE)

Search for pattern in x. if fixed = FALSE then pattern is a regular expression. Else pattern is a text string. returns matching indices

grep(“A”, c(“b”, “A”, “c”), fixed = TRUE) returns 2

toupper(x)

Upper case

x <- “MiXeD Case”

toupper(x)

tolower(x)

Lower case

tolower(x)


User Defined Function

We can create our own function in R. Let’s create a function called pow() :

Example 1:

pow <- function(x,y){
result <- x^y
print(result)

Calling Function

We can call the above function pow() as follows:

> pow(9,2)

Output will be:

[1] 81

Named Arguments

In the above function calls, the position of formal argument and actual argument must be in order.

Means from the above example of function call pow(9, 2), the formal arguments x and y are assigned 9 and 2 respectively.

We can also call the function by name. when calling the function in this way, the order of the actual argument does not matter.

For example:

> pow(9, 2)
[1] 81
> pow(x = 9, y= 2)
[1] 81
> pow(y = 2, x = 9)
[1] 81

We can also use named and unnamed arguments in a single call.

> pow(x = 9, 2)
[1] 81
> pow(2, x = 9)
[1] 81

Default values for Arguments

In R, we can assign default values to arguments of a function.

This is done in the function declaration by providing an appropriate value to the formal argument.

Let's add the above example again by adding a default value to y:

pow <- function(x, y = 2){
result <- x^y
print (result)
}

The use of default value to an argument of a function makes it optional when calling the function.

> pow(9)
[1] 81
> pow(3, 3)
[1] 27

Let's see another example of user-defined function.

Example 2:

# creating a function
addition <- function (a, b){
add <- a+b
# returning a value
return(add)
}
#calling the function
addition(20, 30)

Output:

[1] 50

Example 3:

Let's create a user-defined function to accept two matrix arguments and do matrix operation with the same:

MatSum<-function(M1,M2){
  print("The Matrix1")
  print(M1)
  print("The Matrix2")
  print(M2)
  summat<-M1+M2
  print("Sum of Matrices")
  print(summat)
}
Mat1 <- matrix(1:9, nrow = 3,ncol=3,byrow = TRUE)
Mat2 <- matrix(0:8, nrow = 3,ncol=3,byrow = TRUE)
MatSum(Mat1,Mat2)

Output:

[1] "The Matrix1"
      [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
[1] "The Matrix2"
      [,1] [,2] [,3]
[1,]    0    1    2
[2,]    3    4    5
[3,]    6    7    8
[1] "Sum of Matrices"
       [,1] [,2] [,3]
[1,]    1    3    5
[2,]    7    9   11
[3,]   13   15   17

Example 4:

Create a function to accept a name from the user.
uname <- function()
{
  str <- readline(prompt="Enter the Name: ")
  return(as.character(str))
}
print(uname())

Output:

Enter the Name: Nikita
[1] "Nikita"
Reference: https://www.guru99.com/r-functions-programming.html https://swcarpentry.github.io/r-novice-inflammation/02-func-R/

Related Topics

R Inheritance

One the main concept of object oriented programming is inheritance which allows us to define a new class of existing classes. This means that we can derive new classes from...

5 minutes read.

Introduction to R Programming

What is R Programming? R is a programming language which provides an environment for software used for statistical analysis, graphics representation and reporting. It possesses an extensive catalog of...

4 minutes read.

Logistic Regression in R Programming

Logistic Regression is a classification supervised machine learning algorithm in R programming. Logistic Regression can also be termed Binomial Logistic Regression, Binary Logistic Regression, or Logit Model. Logistic Regression is...

4 minutes read.

Binomial Distribution in R Programming

In this article, we will talk about the Binomial distribution in R programming. The binomial distribution is a type of probability distribution. As it is a discrete distribution, it will...

3 minutes read.

R Data Types

Data types are used to define the size and type of the variable. In R, there is no need to declare a variable as some data types. The variables are...

4 minutes read.

R Line Graphs

Line graph or line chart is a graph that connects a series of points by drawing segments between them. A line graph represents the relationship between 2 variables. These points...

2 minutes read.

R Switch Statement

It is an alternate way to a nested if…else statement. A switch statement permits an expression to be tested against a list of case values. In short, we can say...

1 minute read.

Normal Distribution in R Programming

In statistics, the normal distribution is a type of probability function. Normal distribution tells the user about the distribution of data values in the dataset. It is a very important...

3 minutes read.

R Operators

A symbol that tells the compiler to perform specific mathematical or logical operations is called operator. R language supports mainly 5 different types of operators, which are listed below: Arithmetic...

3 minutes read.

Linear Regression in R Programming

Linear Regression is an unsupervised machine learning algorithm in R programming. Linear Regression is a type of regression analysis that shows the relationship between two or more variables. And one...

3 minutes read.

R Basic Data Types

Data types are used to define the size and type of the variable. In R, there is no need to declare a variable as some data types. The variables are...

4 minutes read.

Bubble Chart in R Programming

In this article, we will talk about another type of chart in R programming, i.e., the Bubble chart. A bubble chart is a type of data visualization chart that helps display multiple...

4 minutes read.

How to create Histograms in R

R Histograms A Histogram is the graphical representation of the distribution of numeric data. It takes only one numeric variable as input. The variable is cut into several bars (also called...

2 minutes read.

R Excel Files

Microsoft Excel is the spreadsheet program which stores data in the .xls and .xlsx format. R has the facility to read directly from these files using some excel specific packages....

2 minutes read.

Various types of Charts in R Programming

As we know, R Language is mostly used for analyzing the data and statistics purposes to represent our data graphically & pictorially in R studio. Charts and graphs are plotted in...

4 minutes read.

Poisson Distribution in R Programming

Poisson distribution is a type of distribution that deals with the probability distribution of the data values by taking the mean into consideration. Poisson distribution will estimate the probability value for...

3 minutes read.

Pie Charts in R Programming

R programming has various libraries to plot various types of charts and graphs. A pie chart is a circular statistical chart or graph, which is divided into slices to represent the numerical...

4 minutes read.

How to make Boxplots in R

R Boxplots Boxplot is a measure of how well the data is distributed in a data set. It is used to give a summary of one or several numeric variables. The...

3 minutes read.

R Functions

In programming, a function is a group of instructions that you want to use repeatedly, because of their complexity, are better self-contained in sub-program and called when needed. Hence, we can...

4 minutes read.

First R Program

First  Hello World R Program As a convention, our first R program will be the “Hello World!” program. We can run our R program either at R command prompt or we...

3 minutes read.