i

R Programming Complete Tutorial

R Functions

A function is a set of statements organized together to perform a specific task.A programmer builds a function to avoid repeating the same task or reduce complexity.Functions are used to logically break our code into simpler parts, which become easy to maintain and understand.

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

A function should be:

Written to carry out specified tasks

May or may not include arguments

Contain a body

It may return one or more values.

Function syntax:

Where,

Function_Name− This is the actual name of the function. It is stored in the R environment as an object with this name.

Function Body − The body of a function includes a set of statements describing what the function does.

Arguments − An argument is a placeholder. When a function is invoked, we pass a value to the argument. Also, arguments can have default values.

 Arguments are optional; that is, a function may contain no arguments. 

Return Value − The return value of a function is the last expression in the function body to be evaluated.

User-defined function

In this section, we will go through different alternatives for user-defined functions.

Case 1: One argument function

Case 2: Multi arguments function

Case 3: Function call with default argument

When to use a Function:

1. Code that gets reused

2. Hiding complexity

Let's build a Function

  • There are two major scales in temperature (Fahrenheit and Celsius), and we need to convert them regularly. ( Reuse)

    • Formula: C= (F-32)* 5/9

R Code: