0% found this document useful (0 votes)
18 views41 pages

Unit 2

The document outlines decision-making structures and loops in R programming, detailing various statements such as if, if...else, switch, and different types of loops like repeat, while, and for. It also explains the usage of control statements like break and next, as well as the concept of functions, including built-in and user-defined functions. Examples are provided to illustrate the syntax and functionality of these programming constructs.

Uploaded by

gayathrinaik12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views41 pages

Unit 2

The document outlines decision-making structures and loops in R programming, detailing various statements such as if, if...else, switch, and different types of loops like repeat, while, and for. It also explains the usage of control statements like break and next, as well as the concept of functions, including built-in and user-defined functions. Examples are provided to illustrate the syntax and functionality of these programming constructs.

Uploaded by

gayathrinaik12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

R - Decision making

Decision making structures require the programmer to specify one or more


conditions to be evaluated or tested by the program, along with a statement
or statements to be executed if the condition is determined to be true, and
optionally, other statements to be executed if the condition is determined to
be false.

Following is the general form of a typical decision making structure found in


most of the programming languages −

R provides the following types of decision making statements. Click the


following links to check their detail.

Sr.N
Statement & Description
o.

if statement
1
An if statement consists of a Boolean expression followed by one or
more statements.

if...else statement
2
An if statement can be followed by an optional else statement,
which executes when the Boolean expression is false.

switch statement
3
A switch statement allows a variable to be tested for equality
against a list of values.
R - If Statement
An if statement consists of a Boolean expression followed by one or more
statements.

Syntax
The basic syntax for creating an if statement in R is −
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true.
}
If the Boolean expression evaluates to be true, then the block of code inside
the if statement will be executed. If Boolean expression evaluates to
be false, then the first set of code after the end of the if statement (after the
closing curly brace) will be executed.

Flow Diagram

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
Live Demo

x <-30L
if(is.integer(x)){
print("X is an Integer")
}

When the above code is compiled and executed, it produces the following
result −

[1] "X is an Integer"


R - If...Else Statement
An if statement can be followed by an optional else statement which
executes when the boolean expression is false.

Syntax
The basic syntax for creating an if...else statement in R is −
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true.
} else {
// statement(s) will execute if the boolean expression is false.
}
If the Boolean expression evaluates to be true, then the if block of code will
be executed, otherwise else block of code will be executed.

Flow Diagram

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
Live Demo

x <- c("what","is","truth")

if("Truth"%in% x){
print("Truth is found")
}else{
print("Truth is not found")
}
When the above code is compiled and executed, it produces the following
result −

[1] "Truth is not found"

Here "Truth" and "truth" are two different strings.

The if...else if...else Statement


An if statement can be followed by an optional else if...else statement,
which is very useful to test various conditions using single if...else if
statement.
When using if, else if, else statements there are few points to keep in mind.
 An if can have zero or one else and it must come after any else if's.
 An if can have zero to many else if's and they must come before the
else.
 Once an else if succeeds, none of the remaining else if's or else's will
be tested.

Syntax
The basic syntax for creating an if...else if...else statement in R is −
if(boolean_expression 1) {
// Executes when the boolean expression 1 is true.
} else if( boolean_expression 2) {
// Executes when the boolean expression 2 is true.
} else if( boolean_expression 3) {
// Executes when the boolean expression 3 is true.
} else {
// executes when none of the above condition is true.
}

Example
Live Demo

x <- c("what","is","truth")

if("Truth"%in% x){
print("Truth is found the first time")
}elseif("truth"%in% x){
print("truth is found the second time")
}else{
print("No truth found")
}

When the above code is compiled and executed, it produces the following
result −

[1] "truth is found the second time"

R - Switch Statement
switch statement
In this switch function expression is matched to list of cases. If a match is
found then it prints that case’s value. No default case is available here. If
no case is matched it outputs NULL as shown in example.

A switch statement allows a variable to be tested for equality against a


list of values. Each value is called a case, and the variable being switched
on is checked for each case.

Syntax

The basic syntax for creating a switch statement in R is −

switch(expression, case1, case2, case3....)

The following rules apply to a switch statement −

 If the value of expression is not a character string it is coerced to


integer.
 You can have any number of case statements within a switch. Each
case is followed by the value to be compared to and a colon.
 If the value of the integer is between 1 and nargs()−1 (The max
number of arguments)then the corresponding element of case
condition is evaluated and the result returned.
 If expression evaluates to a character string then that string is
matched (exactly) to the names of the elements.
 If there is more than one match, the first matching element is
returned.
 No Default argument is available.
 In the case of no match, if there is a unnamed element of ... its
value is returned. (If there is more than one such argument an error
is returned.)
Flow Diagram

Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.

Example
Live Demo

x <-switch(
3,
"first",
"second",
"third",
"fourth"
)
print(x)

When the above code is compiled and executed, it produces the following
result −

[1] "third"
R - Loops
There may be a situation when you need to execute a block of code several
number of times. In general, statements are executed sequentially. The first
statement in a function is executed first, followed by the second, and so on.

Programming languages provide various control structures that allow for


more complicated execution paths.
A loop statement allows us to execute a statement or group of statements
multiple times and the following is the general form of a loop statement in
most of the programming languages −

R programming language provides the following kinds of loop to handle


looping requirements. Click the following links to check their detail.

Sr.N
Loop Type & Description
o.

repeat loop
1
Executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable.

while loop
2
Repeats a statement or group of statements while a given condition is
true. It tests the condition before executing the loop body.

for loop
3
Like a while statement, except that it tests the condition at the end of
the loop body.

Loop Control Statements

Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that
scope are destroyed.

R supports the following control statements. Click the following links to check
their detail.
Sr.N
Control Statement & Description
o.

break statement
1
Terminates the loop statement and transfers execution to the
statement immediately following the loop.

Next statement
2
The next statement simulates the behavior of R switch.

Repeat loop
The Repeat loop executes the same code again and again until a stop
condition is met.

Syntax

The basic syntax for creating a repeat loop in R is −

repeat {
commands
if(condition) {
break
}
}

Flow Diagram

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.
Example
Live Demo

v <- c("Hello","loop")
cnt<-2

repeat {
print(v)
cnt<- cnt+1

if(cnt>5){
break
}
}

When the above code is compiled and executed, it produces the following
result −

[1] "Hello" "loop"


[1] "Hello" "loop"
[1] "Hello" "loop"
[1] "Hello" "loop"

R - While Loop
The While loop executes the same code again and again until a stop
condition is met.

Syntax

The basic syntax for creating a while loop in R is −

while (test_expression) {
statement
}
Flow Diagram

Here key point of the while loop is that the loop might not ever run. When
the condition is tested and the result is false, the loop body will be skipped
and the first statement after the while loop will be executed.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
Live Demo

v <-c("Hello","while loop")
cnt<-2

while(cnt<7){
print(v)
cnt=cnt+1
}

When the above code is compiled and executed, it produces the following
result −

[1] "Hello" "while loop"


[1] "Hello" "while loop"
[1] "Hello" "while loop"
[1] "Hello" "while loop"
[1] "Hello" "while loop"
R - For Loop
A For loop is a repetition control structure that allows you to efficiently write
a loop that needs to execute a specific number of times.

Syntax
The basic syntax for creating a for loop statement in R is −
for (value in vector) {
statements
}

Flow Diagram

R’s for loops are particularly flexible in that they are not limited to integers,
or even numbers in the input. We can pass character vectors, logical vectors,
lists or expressions.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
Live Demo

v <-LETTERS[1:4]
for(iin v){
print(i)
}
When the above code is compiled and executed, it produces the following
result −

[1] "A"
[1] "B"
[1] "C"
[1] "D"

R - Break Statement
The break statement in R programming language has the following two
usages −

 When the break statement is encountered inside a loop, the loop is


immediately terminated and program control resumes at the next
statement following the loop.
 It can be used to terminate a case in the switch statement (covered in
the next chapter).

Syntax

The basic syntax for creating a break statement in R is −

break

Flow Diagram
Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
Live Demo

v <- c("Hello","loop")
cnt<-2

repeat {
print(v)
cnt<-cnt+1

if(cnt>5){
break
}
}

When the above code is compiled and executed, it produces the following
result −

[1] "Hello" "loop"


[1] "Hello" "loop"
[1] "Hello" "loop"
[1] "Hello" "loop"

R - Next Statement
The next statement in R programming language is useful when we want to
skip the current iteration of a loop without terminating it. On encountering
next, the R parser skips further evaluation and starts next iteration of the
loop.

Syntax

The basic syntax for creating a next statement in R is −

next
Flow Diagram

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Example
Live Demo

v <-LETTERS[1:6]
for(iin v){

if(i=="D"){
next
}
print(i)
}

When the above code is compiled and executed, it produces the following
result −
[1] "A"
[1] "B"
[1] "C"
[1] "E"
[1] "F"

R Functions

A set of statements which are organized together to perform a specific task is known as a
function. R provides a series of in-built functions, and it allows the user to create their own
functions. Functions are used to perform tasks in the modular approach.

Functions are used to avoid repeating the same task and to reduce complexity. To understand
and maintain our code, we logically break it into smaller parts using the function. A function
should be
1. Written to carry out a specified task.
2. May or may not have arguments
3. Contain a body in which our code is written.
4. May or may not return one or more output values.

"An R function is created by using the keyword function." There is the following syntax
of R function:

1. func_name <- function(arg_1, arg_2, ...)


2. {
3. Function body
4. }

Components of Functions

There are four components of function, which are as follows:

Function Name

The function name is the actual name of the function. In R, the function is stored as an object
with its name.

Arguments

In R, an argument is a placeholder. In function, arguments are optional means a function may


or may not contain arguments, and these arguments can have default values also. We pass a
value to the argument when a function is invoked.

Function Body

The function body contains a set of statements which defines what the function does.

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

Function Types

Similar to the other languages, R also has two types of function, i.e. Built-in
Function and User-defined Function. In R, there are lots of built-in functions which we can
directly call in the program without defining them. R also allows us to create our own
functions.

Built-in function

The functions which are already created or defined in the programming framework are
known as built-in functions. User doesn't need to create these types of functions, and these
functions are built into an application. End-users can access these functions by simply calling
it. R have different types of built-in functions such as seq(), mean(), max(), and sum(x) etc.

1. # Creating sequence of numbers from 32 to 46.


2. print(seq(32,46))
3.
4. # Finding the mean of numbers from 22 to 80.
5. print(mean(22:80))
6.
7. # Finding the sum of numbers from 41 to 70.
8. print(sum(41:70))

Output:
User-defined function

R allows us to create our own function in our program. A user defines a user-define function
to fulfill the requirement of user. Once these functions are created, we can use these functions
like in-built function.

1. # Creating a function without an argument.


2. new.function <- function() {
3. for(i in 1:5) {
4. print(i^2)
5. }
6. }
7.
8. new.function()

Output:

ADVERTISEMENT

Function calling with an argument

We can easily call a function by passing an appropriate argument in the function. Let see an
example to see how a function is called.

1. # Creating a function to print squares of numbers in sequence.


2. new.function <- function(a) {
3. for(i in 1:a) {
4. b <- i^2
5. print(b)
6. }
7.
8. # Calling the function new.function supplying 10 as an argument.
9. new.function(10)
Output:

Function calling with no argument

In R, we can call a function without an argument in the following way

1. # Creating a function to print squares of numbers in sequence.


2. new.function <- function() {
3. for(i in 1:5) {
4. a <- i^2
5. print(a)
6. }
7. }
8.
9. # Calling the function new.function with no argument.
10. new.function()

Output:
Function calling with Argument Values

We can supply the arguments to a function call in the same sequence as defined in the
function or can supply in a different sequence but assigned them to the names of the
arguments.

1. # Creating a function with arguments.


2. new.function <- function(x,y,z) {
3. result <- x * y + z
4. print(result)
5. }
6.
7. # Calling the function by position of arguments.
8. new.function(11,13,9)
9.
10. # Calling the function by names of the arguments.
11. new.function(x = 2, y = 5, z = 3)

Output:

Function calling with default arguments

To get the default result, we assign the value to the arguments in the function definition, and
then we call the function without supplying argument. If we pass any argument in the
function call, then it will get replaced with the default value of the argument in the function
definition.

1. # Creating a function with arguments.


2. new.function <- function(x = 11, y = 24) {
3. result <- x * y
4. print(result)
5. }
6.
7. # Calling the function without giving any argument.
8. new.function()
9.
10. # Calling the function with giving new values of the argument.
11. new.function(4,6)

Output:
R Built-in Functions

The functions which are already created or defined in the programming framework are
known as a built-in function. R has a rich set of functions that can be used to perform almost
every task for the user. These built-in functions are divided into the following categories
based on their functionality.

Math Functions

R provides the various mathematical functions to perform the mathematical calculation.


These mathematical functions are very helpful to find absolute value, square value and much
more calculations. In R, there are the following functions which are used:

S. Function Description Example


No

1. abs(x) It returns the absolute value of x<- -4


input x. print(abs(x))
Output
[1] 4
2. sqrt(x) It returns the square root of x<- 4
input x. print(sqrt(x))
Output
[1] 2
3. ceiling(x) It returns the smallest integer x<- 4.5
which is larger than or equal print(ceiling(x))
to x. Output
[1] 5
4. floor(x) It returns the largest integer, x<- 2.5
which is smaller than or equal print(floor(x))
to x. Output
[1] 2
5. trunc(x) It returns the truncate value of x<-
input x. c(1.2,2.5,8.1)
print(trunc(x))
Output
[1] 1 2 8
6. round(x, It returns round value of input x<- -4
digits=n) x. print(abs(x))
Output
4
7. cos(x), It returns cos(x), sin(x) value x<- 4
sin(x), tan(x) of input x. print(cos(x))
print(sin(x))
print(tan(x))
Output
[1] -06536436
[2] -0.7568025
[3] 1.157821
8. log(x) It returns natural logarithm of x<- 4
input x. print(log(x))
Output
[1] 1.386294
9. log10(x) It returns common logarithm x<- 4
of input x. print(log10(x))
Output
[1] 0.60206
10. exp(x) It returns exponent. x<- 4
print(exp(x))
Output
[1] 54.59815

String Function

R provides various string functions to perform tasks. These string functions allow us to
extract sub string from string, search pattern etc. There are the following string functions in
R:

S. Function Description Example


No

1. substr(x, It is used to a <- "987654321"


start=n1,stop=n2) extract substrings substr(a, 3, 3)
in a character Output
vector. [1] "3"

2. grep(pattern, x , It searches for st1 <-


ignore.case=FALSE, pattern in x. c('abcd','bdcd','abcdabcd')
fixed=FALSE) pattern<- '^abc'
print(grep(pattern, st1))
Output
[1] 1 3
3. sub(pattern, It finds pattern in st1<- "England is beautiful
replacement, x, x and replaces it but no the part of EU"
ignore.case =FALSE, with replacement sub("England', "UK", st1)
fixed=FALSE) (new) text. Output
[1] "UK is beautiful but not
a part of EU"
4. paste(..., sep="") It concatenates paste('one',2,'three',4,'five')
strings after Output
using sep string
[1] one 2 three 4 five
to separate them.

5. strsplit(x, split) It splits the a<-"Split all the character"


elements of print(strsplit(a, ""))
character vector Output
x at split point. [[1]]
[1] "split" "all" "the"
"character"
6. tolower(x) It is used to st1<- "shuBHAm"
convert the string print(tolower(st1))
into lower case. Output
[1] shubham
7. toupper(x) It is used to st1<- "shuBHAm"
convert the string print(toupper(st1))
into upper case. Output
[1] SHUBHAM

Statistical Probability Functions

R provides various statistical probability functions to perform statistical task. These statistical
functions are very helpful to find normal density, normal quantile and many more calculation.
In R, there are following functions which are used:

S. Function Description Example


No

1. dnorm(x, m=0, sd=1, It is used to find the height of a <- seq(-7, 7, by=0.1)
log=False) the probability distribution at b <- dnorm(a, mean=2.5,
each point to a given mean and sd=0.5)
standard deviation png(file="dnorm.png")
plot(x,y)
dev.off()
2. pnorm(q, m=0, sd=1, it is used to find the probability a <- seq(-7, 7, by=0.2)
lower.tail=TRUE, of a normally distributed b <- dnorm(a, mean=2.5, sd=2)
log.p=FALSE) random numbers which are less png(file="pnorm.png")
than the value of a given plot(x,y)
number. dev.off()

3. qnorm(p, m=0, sd=1) It is used to find a number a <- seq(1, 2, by=002)


whose cumulative value b <- qnorm(a, mean=2.5,
matches with the probability sd=0.5)
value. png(file="qnorm.png")
plot(x,y)
dev.off()
4. rnorm(n, m=0, sd=1) It is used to generate random y <- rnorm(40)
numbers whose distribution is png(file="rnorm.png")
normal. hist(y, main="Normal
Distribution")
dev.off()
5. dbinom(x, size, prob) It is used to find the probability a<-seq(0, 40, by=1)
density distribution at each b<- dbinom(a, 40, 0.5)
point. png(file="pnorm.png")
plot(x,y)
dev.off()
6. pbinom(q, size, prob) It is used to find the cumulative a <- pbinom(25, 40,0.5)
probability (a single value print(a)
representing the probability) of Output
an event.
[1] 0.9596548
7. qbinom(p, size, prob) It is used to find a number a <- qbinom(0.25, 40,01/2)
whose cumulative value print(a)
matches the probability value. Output
[1] 18
8. rbinom(n, size, prob) It is used to generate required a <- rbinom(6, 140,0.4)
number of random values of a print(a)
given probability from a given Output
sample. [1] 55 61 46 56 58 49

9. dpois(x, lamba) it is the probability of x dpois(a=2,


successes in a period when the lambda=3)+dpois(a=3,
expected number of events is lambda=3)+dpois(z=4, labda=4)
lambda (λ) Output
[1] 0.616115
10. ppois(q, lamba) It is a cumulative probability of ppois(q=4, lambda=3,
less than or equal to q lower.tail=TRUE)-ppois(q=1,
successes. lambda=3, lower.tail=TRUE)
Output
[1] 0.6434504
11. rpois(n, lamba) It is used to generate random rpois(10, 10)
numbers from the poisson [1] 6 10 11 3 10 7 7 8 14
distribution. 12

12. dunif(x, min=0, max=1) This function provide dunif(x, min=0, max=1,
information about the uniform log=FALSE)
distribution on the interval
from min to max. It gives the
density.

13. punif(q, min=0, max=1) It gives the distributed function punif(q, min=0, max=1,
lower.tail=TRUE,
log.p=FALSE)
14. qunif(p, min=0, max=1) It gives the quantile function. qunif(p, min=0, max=1,
lower.tail=TRUE,
log.p=FALSE)
15. runif(x, min=0, max=1) It generates random deviates. runif(x, min=0, max=1)

Other Statistical Function

Apart from the functions mentioned above, there are some other useful functions which helps
for statistical purpose. There are the following functions:
S. Function Description Example
No

1. mean(x, trim=0, It is used to find the a<-c(0:10, 40)


na.rm=FALSE) mean for x object xm<-mean(a)
print(xm)
Output
[1] 7.916667
2. sd(x) It returns standard a<-c(0:10, 40)
deviation of an object. xm<-sd(a)
print(xm)
Output
[1] 10.58694
3. median(x) It returns median. a<-c(0:10, 40)
xm<-meadian(a)
print(xm)
Output
[1] 5.5
4. quantilie(x, It returns quantile
probs) where x is the numeric
vector whose
quantiles are desired
and probs is a numeric
vector with
probabilities in [0, 1]

5. range(x) It returns range. a<-c(0:10, 40)


xm<-range(a)
print(xm)
Output
[1] 0 40
6. sum(x) It returns sum. a<-c(0:10, 40)
xm<-sum(a)
print(xm)
Output
[1] 95
7. diff(x, lag=1) It returns differences a<-c(0:10, 40)
with lag indicating xm<-diff(a)
which lag to use. print(xm)
Output
[1] 1 1 1 1 1 1 1
1 1 1 30
8. min(x) It returns minimum a<-c(0:10, 40)
value. xm<-min(a)
print(xm)
Output
[1] 0
9. max(x) It returns maximum a<-c(0:10, 40)
value xm<-max(a)
print(xm)
Output
[1] 40
10. scale(x, Column center or a <- matrix(1:9,3,3)
center=TRUE, standardize a matrix. scale(x)
scale=TRUE) Output
[,1]
[1,] -0.747776547
[2,] -0.653320562
[3,] -0.558864577
[4,] -0.464408592
[5,] -0.369952608
[6,] -0.275496623
[7,] -0.181040638
[8,] -0.086584653
[9,] 0.007871332
[10,] 0.102327317
[11,] 0.196783302
[12,] 3.030462849
attr(,"scaled:center")
[1] 7.916667
attr(,"scaled:scale")
[1] 10.58694

A quick definition

Lazy evaluation is a programming strategy that allows a symbol to be evaluated only when
needed. In other words, a symbol can be defined (e.g in a function), and it will only be
evaluated when it is needed (and that moment can be never). This is why you can do:

plop <- function(a, b)

{
a *10

plop(4)

## [1] 40

Here,
b
is defined as a function argument, but never evaluated. So no error. This strategy is called
“lazy” as it does “the strict minimum” of evaluation (remember that evaluation is looking for
the value of a symbol).

Lazy evaluation means you can also do:

plop(a = 4, b = non_existing_variable)
## [1] 40

As

b
is never evaluated, we don’t have any problem, R never tries to look for the value of
non_existing_variable
.

We can also find it in control structure:

if(TRUE){
12
}else{
no_variable
}
## [1] 12

And of course this works on the other side:

if(FALSE){
no_variable
}else{
12
}
## [1] 12

Only the TRUE part is evaluated. You can also find it in :

if(TRUE||no_variable){

12

## [1] 12
Why lazy eval

Lazy evaluation is not R-restricted: it is also found in other languages (mainly functional
languages). Its opposite is strict/eager evaluation, which is the default in most programming
languages.
Lazy evaluation is implemented in R as it allows a program to be more efficient when used
interactively: only the necessary symbols are evaluated, that is to say that only the
needed objects will be loaded in memory and/or looked for. The downside being that it
can make a program less predictable, as you are never 100% sure a symbol will be evaluated
(but this is for more advanced use-cases).

It’s a typical mechanism for functional language, as it allows functions to be defined without
any values in it. That means that you can create this object without a and b having a value.

ping <- function(a,b){

a+b

}
The expression given as function arguments are not evaluated before the function is called.
Instead, the expressions are packaged together with the environment in which they should be
evaluated and it is this package that is passed to the function. Evaluation only takes place
when the argument is required.

R Functions

In simple terms, a function is a block of statements that can be used repeatedly in a program.
R provides many built-in functions and allows programmers to define their own functions.

Syntax

Here’s the syntax of a function in R:

Lazy Evaluation

R functions perform lazy evaluation that dramatically extends the expressive power of
functions. It is the technique of not evaluating arguments unless and until they are needed in
the function.

myfunc<- function(x, y) {
if(!x){
return(y)
}
else{
return(x)
}
}

# y is not evaluated so not including it causes no harm


myfunc(6)
[1] 6

# y is evaluated so not including it raises error


myfunc(0)
Error in myfunc(0) : argument "y" is missing, with no default

R - Functions

A function is a set of statements organized together to perform a specific task. R has a large
number of in-built functions and the user can create their own functions.

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

The function in turn performs its task and returns control to the interpreter as well as any
result which may be stored in other objects.

Function Definition
An R function is created by using the keyword function. The basic syntax of an R function
definition is as follows −
function_name<- function(arg_1, arg_2, ...) {
Function body
}
Function Components

The different parts of a function are −

 Function Name − This is the actual name of the function. It is stored in R


environment as an object with this name.
 Arguments − An argument is a placeholder. When a function is invoked, you pass a
value to the argument. Arguments are optional; that is, a function may contain no
arguments. Also arguments can have default values.
 Function Body − The function body contains a collection of statements that defines
what the function does.
 Return Value − The return value of a function is the last expression in the function
body to be evaluated.
R has many in-built functions which can be directly called in the program without defining
them first. We can also create and use our own functions referred as user defined functions.
Built-in Function
Simple examples of in-built functions are seq(), mean(), max(), sum(x) and paste(...) etc.
They are directly called by user written programs
# Create a sequence of numbers from 32 to 44.
print(seq(32,44))

# Find mean of numbers from 25 to 82.


print(mean(25:82))

# Find sum of numbers frm 41 to 68.


print(sum(41:68))

When we execute the above code, it produces the following result −

[1] 32 33 34 35 36 37 38 39 40 41 42 43 44
[1] 53.5
[1] 1526

User-defined Function

We can create user-defined functions in R. They are specific to what a user wants and once
created they can be used like the built-in functions. Below is an example of how a function is
created and used.

# Create a function to print squares of numbers in sequence.


new.function<-function(a){
for(iin1:a){
b <- i^2
print(b)
}
}

Calling a Function
# Create a function to print squares of numbers in sequence.
new.function<-function(a){
for(iin1:a){
b <- i^2
print(b)
}
}

# Call the function new.function supplying 6 as an argument.


new.function(6)

When we execute the above code, it produces the following result −

[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36
Calling a Function without an Argument
# Create a function without an argument.
new.function<-function(){
for(iin1:5){
print(i^2)
}
}

# Call the function without supplying an argument.


new.function()

When we execute the above code, it produces the following result −

[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
Calling a Function with Argument Values (by position and by name)

The arguments to a function call can be supplied in the same sequence as defined in the
function or they can be supplied in a different sequence but assigned to the names of the
arguments.

# Create a function with arguments.


new.function<-function(a,b,c){
result <- a * b + c
print(result)
}

# Call the function by position of arguments.


new.function(5,3,11)

# Call the function by names of the arguments.


new.function(a =11, b =5, c =3)

When we execute the above code, it produces the following result −

[1] 26
[1] 58

Calling a Function with Default Argument

We can define the value of the arguments in the function definition and call the function
without supplying any argument to get the default result. But we can also call such functions
by supplying new values of the argument and get non default result.

# Create a function with arguments.


new.function<-function(a =3, b =6){
result <- a * b
print(result)
}
# Call the function without giving any argument.
new.function()

# Call the function with giving new values of the argument.


new.function(9,5)

When we execute the above code, it produces the following result −

[1] 18
[1] 45
Lazy Evaluation of Function

Arguments to functions are evaluated lazily, which means so they are evaluated only when
needed by the function body.

# Create a function with arguments.


new.function<-function(a, b){
print(a^2)
print(a)
print(b)
}

# Evaluate the function without supplying one of the arguments.


new.function(6)

When we execute the above code, it produces the following result −

[1] 36
[1] 6
Error in print(b) : argument "b" is missing, with no default

R Return Value from Function

In this article, you will learn to return a value from a function in R. You'll also learn to use
functions without the return function.
Many times, we will require our functions to do some processing and return the result. This is
accomplished with the return() function in R.

Syntax of return()
The syntax of the return() function is:
return(expression)
Here, expression is evaluated, and its value is stored as the result of the function.
The value specified in the return() statement is passed as the output of the function.
Example of return()
Let us look at an example which will return whether a given number is positive, negative or
zero.

check <- function(x) {


if (x >0) {
result <- "Positive"
}
elseif (x <0) {
result <- "Negative"
}
else {
result <- "Zero"
}
return(result)
}

check(1)
check(-10)
check(0)
Output
[1] "Positive"
[1] "Negative"
[1] "Zero"

Functions without return()


If there are no explicit returns from a function, the value of the last evaluated expression is
returned automatically in R.
For example, the following is equivalent to the above function.

check <- function(x) {


if (x >0) {
result <- "Positive"
}
elseif (x <0) {
result <- "Negative"
}
else {
result <- "Zero"
}
result
}
We generally use explicit return() functions to return a value immediately from a function.
If it is not the last statement of the function, it will prematurely end the function bringing the
control to the place from which it was called.

check <- function(x) {


if (x>0) {
return("Positive")
}
elseif (x<0) {
return("Negative")
}
else {
return("Zero")
}
}
In the above example, if x > 0, the function immediately returns "Positive" without
evaluating the rest of the body.

Multiple Returns
The return() function can return only a single object. If we want to return multiple values in
R, we can use a list (or other objects) and return it.
Following is an example:

multi_return<- function() {
my_list<- list("color" = "red", "size" = 20, "shape" = "round")
return(my_list)
}
# call function multi_return() and assign the result to variable a
a <- multi_return()
a$color
a$size
a$shape
Output
[1] "red"
[1] 20
[1]"round"
Here, the function multi_return() creates a list object my_list, assigns some values to its
elements, and then returns the entire list as the output of the function.
The list contains three elements: "color" with the value "red", "size" with the value 20,
and "shape" with the value "round".
The multi_return() function is called and its result is assigned to the variable a.
Here,
 a$color - accesses the value of the "color" element
 a$size - accesses the value of the "size" element
 a$shape - accesses the value of the "shape" element

R Functions

In simple terms, a function is a block of statements that can be used repeatedly in a program.
R provides many built-in functions and allows programmers to define their own functions.

Syntax

Here’s the syntax of a function in R:

Recursive Function in R:
Recursion is when the function calls 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.
Since the loops increase the memory we use the recursion. The recursive function uses the
concept of recursion to perform iterative tasks they call themselves, again and again, which
acts as a loop. These kinds of functions need a stopping condition so that they can stop
looping continuously. Recursive functions call themselves. They break down the problem
into smaller components. The function() calls itself within the original function() on each of
the smaller components. After this, the results will be put together to solve the original
problem.
Example: Factorial using Recursion in R
 R

rec_fac<- function(x){

if(x==0 || x==1)
{

return(1)

else

return(x*rec_fac(x-1))

rec_fac(5)

Output:
[1] 120
Here, rec_fac(5) calls rec_fac(4), which then calls rec_fac(3), and so on until the input
argument x, has reached 1. The function returns 1 and is destroyed. The return value is
multiplied by the argument value and returned. This process continues until the first
function call returns its output, giving us the final result.
Example: Sum of Series Using Recursion
Recursion in R is most useful for finding the sum of self-repeating series. In this example,
we will find the sum of squares of a given series of numbers. Sum = 1 2+22+…+N2
Example:
 R

sum_series<- function(vec){

if(length(vec)<=1)

return(vec^2)

else

return(vec[1]^2+sum_series(vec[-1]))

}
}

series <- c(1:10)

sum_series(series)

Output:
[1] 385

 R

sum_n<- function(n) {

if (n == 1) {

return(1)

} else{

return(n + sum_n(n-1))

# Test the sum_n function

sum_n(5)

Output:
[1] 15
In this example, the sum_n function recursively increases n until it reaches 1, which is the
base case of the recursion, by adding the current value of n to the sum of the first n-1
values.
 R

exp_n<- function(base, n) {

if (n == 0) {

return(1)

} else{

return(base * exp_n(base, n-1))


}

# Test the exp_n function

exp_n(4, 5)

Output:
[1] 1024
In this example, the base case of the recursion is represented by the exp_n function, which
recursively multiplies the base by itself n times until n equals 0.

Key Features of R Recursion


 The use of recursion, often, makes the code shorter and it also looks clean.
 It is a simple solution for a few cases.
 It expresses in a function that calls itself.
Applications of Recursion in R
 Recursive functions are used in many efficient programming techniques like dynamic
programming language(DSL) or divide-and-conquer algorithms.
 In dynamic programming, for both top-down as well as bottom-up approaches, recursion
is vital for performance.
 In divide-and-conquer algorithms, we divide a problem into smaller sub-problems that
are easier to solve. The output is then built back up to the top. Recursion has a similar
process, which is why it is used to implement such algorithms.
 In its essence, recursion is the process of breaking down a problem into many smaller
problems, these smaller problems are further broken down until the problem left is
trivial. The solution is then built back up piece by piece.

Types of Recursion in R
1. Direct Recursion: The recursion that is direct involves a function calling itself directly.
This kind of recursion is the easiest to understand.

2. Indirect Recursion: An indirect recursion is a series of function calls in which one


function calls another, which in turn calls the original function.

3. Mutual Recursion: Multiple functions that call each other repeatedly make up mutual
recursion. To complete a task, each function depends on the others.

4. Nested Recursion: Nested recursion happens when one recursive function calls another
recursively while passing the output of the first call as an argument. The arguments of
one recursion are nested inside of this one.

5. Structural Recursion: Recursion that is based on the structure of the data is known as
structural recursion. It entails segmenting a complicated data structure into smaller pieces
and processing each piece separately.
Recursion
R also accepts function recursion, which means a defined function can call itself.

Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the
benefit of meaning that you can loop through data to reach a result.

The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never
terminates, or one that uses excess amounts of memory or processor power. However, when written correctly,
recursion can be a very efficient and mathematically-elegant approach to programming.

In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use the k variable as
the data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0
(i.e. when it is 0).

To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and
modifying it.

Example
tri_recursion<- function(k) {
if (k > 0) {
result <- k + tri_recursion(k - 1)
print(result)
} else {
result = 0
return(result)
}
}
tri_recursion(6)

output
[1] 1
[1] 3
[1] 6
[1] 10
[1] 15
[1] 21

You might also like