Unit Ii Notes FDS

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 32

UNIT II

Conditionals and Control Flow: Relational Operators, Relational Operators and Vectors,
Logical
Operators, Logical Operators and Vectors, Conditional Statements. Iterative Programming in
R:
Introduction, While Loop, For Loop, Looping Over List. Functions in
R: Introduction, writing a Function in R, Nested Functions, Function Scoping, Recursion,
Loading an
R Package, Mathematical Function in R
R Operators
Operators are the symbols directing the compiler to perform various kinds of operations
between the operands. Operators simulate the various mathematical, logical, and decision
operations performed on a set of Complex Numbers, Integers, and Numericals as input
operands.
R supports majorly four kinds of binary operators between a set of operands. In this article,
we will see various types of operators in R Programming language and their usage.
Types of the operator in R language
 Arithmetic Operators
 Logical Operators
 Relational Operators
 Assignment Operators
 Miscellaneous Operators
Arithmetic Operators
Arithmetic Operators modulo using the specified operator between operands, which may be
either scalar values, complex numbers, or vectors. The R operators are performed element-
wise at the corresponding positions of the vectors.
Addition operator (+)
The values at the corresponding positions of both operands are added. Consider the
following R operator snippet to add two vectors:
R
a <- c (1, 0.1) b <- c (2.33, 4) print (a+b)
Output : 3.33 4.10
Subtraction Operator (-)
The second operand values are subtracted from the first. Consider the following R operator
snippet to subtract two variables:
R
a <- 6 b <- 8.4 print (a-b)
Output : -2.4
Multiplication Operator (*)
The multiplication of corresponding elements of vectors and Integers are multiplied with
the use of the ‘*’ operator.
R
B= c(4,4) C= c(5,5) print (B*C)
Output : 20 20
Division Operator (/)
The first operand is divided by the second operand with the use of the ‘/’ operator.
R
a <- 10 b <- 5 print (a/b)
Output : 2
Power Operator (^)
The first operand is raised to the power of the second operand.
R
a <- 4 b <- 5 print(a^b)
Output : 1024
Modulo Operator (%%)
The remainder of the first operand divided by the second operand is returned.
R
list1<- c(2, 22) list2<-c(2,4) print(list1 %% list2)
Output : 0 2
The following R code illustrates the usage of all Arithmetic R operators.
R
# R program to illustrate # the use of Arithmetic operators vec1 <- c(0, 2) vec2 <- c(2, 3) #
Performing operations on Operands cat ("Addition of vectors :", vec1 + vec2, "\
n") cat ("Subtraction of vectors :", vec1 - vec2, "\n") cat ("Multiplication of
vectors :", vec1 * vec2, "\n") cat ("Division of vectors :", vec1 / vec2, "\n") cat ("Modulo of
vectors :", vec1 %% vec2, "\n") cat ("Power operator :", vec1 ^ vec2)
Output
Addition of vectors : 2 5 Subtraction of vectors : -2 -1 Multiplication of vectors : 0 6
Division of vectors : 0 0.6666667 Modulo of vectors : 0 2 Power operator : 0 8
Logical Operators
Logical Operators in R simulate element-wise decision operations, based on the specified
operator between the operands, which are then evaluated to either a True or False boolean
value. Any non-zero integer value is considered as a TRUE value, be it a complex or real
number.
Element-wise Logical AND operator (&)
Returns True if both the operands are True.
R
list1 <- c(TRUE, 0.1) list2 <- c(0,4+3i) print(list1 & list2)
Output : FALSE TRUE Any non zero integer value is considered as a TRUE value, be it
complex or real number.
Element-wise Logical OR operator (|)
Returns True if either of the operands is True.
R
list1 <- c(TRUE, 0.1) list2 <- c(0,4+3i) print(list1|list2)
Output : TRUE TRUE
NOT operator (!)
A unary operator that negates the status of the elements of the operand.
R
list1 <- c(0,FALSE) print(!list1)
Output : TRUE TRUE
Logical AND operator (&&)
Returns True if both the first elements of the operands are True.
R
list1 <- c(TRUE, 0.1) list2 <- c(0,4+3i) print(list1[1] && list2[1])
Output : FALSE Compares just the first elements of both the lists.
Logical OR operator (||)
Returns True if either of the first elements of the operands is True.
R
list1 <- c(TRUE, 0.1) list2 <- c(0,4+3i) print(list1[1]||list2[1])
Output : TRUE
The following R code illustrates the usage of all Logical Operators in R:
R
# R program to illustrate # the use of Logical
operators vec1 <- c(0,2) vec2 <- c(TRUE,FALSE) # Performing operations on
Operands cat ("Element wise AND :", vec1 & vec2, "\n") cat ("Element wise
OR :", vec1 | vec2, "\n") cat ("Logical AND :", vec1[1] && vec2[1], "\n") cat ("Logical
OR :", vec1[1] || vec2[1], "\n") cat ("Negation :", !vec1)
Output
Element wise AND : FALSE FALSE Element wise OR : TRUE TRUE Logical AND :
FALSE Logical OR : TRUE Negation : TRUE FALSE
Relational Operators
The Relational Operators in R carry out comparison operations between the corresponding
elements of the operands. Returns a boolean TRUE value if the first operand satisfies the
relation compared to the second. A TRUE value is always considered to be greater than the
FALSE.
Less than (<)
Returns TRUE if the corresponding element of the first operand is less than that of the
second operand. Else returns FALSE.
R
list1 <- c(TRUE, 0.1,"apple") list2 <- c(0,0.1,"bat") print(list1<list2)
Output : FALSE FALSE TRUE
Less than equal to (<=)
Returns TRUE if the corresponding element of the first operand is less than or equal to that
of the second operand. Else returns FALSE.
R
list1 <- c(TRUE, 0.1, "apple") list2 <- c(TRUE, 0.1, "bat") # Convert lists to character
strings list1_char <- as.character(list1) list2_char <- as.character(list2) # Compare character
strings print(list1_char <= list2_char)
Output : TRUE TRUE TRUE
Greater than (>)
Returns TRUE if the corresponding element of the first operand is greater than that of the
second operand. Else returns FALSE.
R
list1 <- c(TRUE, 0.1, "apple") list2 <- c(TRUE, 0.1, "bat") print(list1_char > list2_char)
Output : FALSE FALSE FALSE
Greater than equal to (>=)
Returns TRUE if the corresponding element of the first operand is greater or equal to that
of the second operand. Else returns FALSE.
R
list1 <- c(TRUE, 0.1, "apple") list2 <- c(TRUE, 0.1, "bat") print(list1_char >= list2_char)
Output : TRUE TRUE FALSE
Not equal to (!=)
Returns TRUE if the corresponding element of the first operand is not equal to the second
operand. Else returns FALSE.
R
list1 <- c(TRUE, 0.1,'apple') list2 <- c(0,0.1,"bat") print(list1!=list2)
Output : TRUE FALSE TRUE
The following R code illustrates the usage of all Relational Operators in R:
R
# R program to illustrate # the use of Relational operators vec1 <- c(0, 2) vec2 <- c(2, 3) #
Performing operations on Operands cat ("Vector1 less than Vector2 :", vec1 < vec2, "\
n") cat ("Vector1 less than equal to Vector2 :", vec1 <= vec2, "\n") cat ("Vector1 greater than
Vector2 :", vec1 > vec2, "\n") cat ("Vector1 greater than equal to Vector2 :", vec1 >= vec2, "\
n") cat ("Vector1 not equal to Vector2 :", vec1 != vec2, "\n")
Output
Vector1 less than Vector2 : TRUE TRUE Vector1 less than equal to Vector2 : TRUE
TRUE Vector1 greater than Vector2 : FALSE FALSE Vector1 greater than equal to
Vector2 : FALSE FALSE Vector1 not equal to Vector2 : TRUE TRUE
Assignment Operators
Assignment Operators in R are used to assigning values to various data objects in R. The
objects may be integers, vectors, or functions. These values are then stored by the assigned
variable names. There are two kinds of assignment operators: Left and Right
Left Assignment (<- or <<- or =)
Assigns a value to a vector.
R
vec1 = c("ab", TRUE) print (vec1)
Output : "ab" "TRUE"
Right Assignment (-> or ->>)
Assigns value to a vector.
R
c("ab", TRUE) ->> vec1 print (vec1)
Output : "ab" "TRUE"
The following R code illustrates the usage of all Relational Operators in R:
R
# R program to illustrate # the use of Assignment operators vec1 <- c(2:5) c(2:5) -
>> vec2 vec3 <<- c(2:5) vec4 = c(2:5) c(2:5) -> vec5 # Performing operations on
Operands cat ("vector 1 :", vec1, "\n") cat("vector 2 :", vec2, "\n") cat ("vector 3 :", vec3, "\
n") cat("vector 4 :", vec4, "\n") cat("vector 5 :", vec5)
Output
vector 1 : 2 3 4 5 vector 2 : 2 3 4 5 vector 3 : 2 3 4 5 vector 4 : 2 3 4 5 vector 5 : 2 3 4 5
Miscellaneous Operators
Miscellaneous Operator are the mixed operators in R that simulate the printing of sequences
and assignment of vectors, either left or right-handed.
%in% Operator
Checks if an element belongs to a list and returns a boolean value TRUE if the value is
present else FALSE.
R
val <- 0.1 list1 <- c(TRUE, 0.1,"apple") print (val %in% list1)
Output : TRUE Checks for the value 0.1 in the specified list. It exists, therefore, prints
TRUE.
%*% Operator
This operator is used to multiply a matrix with its transpose. Transpose of the matrix is
obtained by interchanging the rows to columns and columns to rows. The number of
columns of the first matrix must be equal to the number of rows of the second matrix.
Multiplication of the matrix A with its transpose, B, produces a square matrix.
Ar∗cxBc∗r−>Pr∗r Ar∗cxBc∗r−>Pr∗r
R
mat = matrix(c(1,2,3,4,5,6),nrow=2,ncol=3) print (mat) print( t(mat)) pro = mat %*% t(mat)
print(pro)
Input : Output :[,1] [,2] [,3]
#original matrix of order 2x3 [1,] 1 3 5 [2,] 2 4 6 [,1] [,2]
#transposed matrix of order 3x2 [1,] 1 2 [2,] 3 4 [3,] 5 6 [,1] [,2]
#product matrix of order 2x2 [1,] 35 44 [2,] 44 56
The following R code illustrates the usage of all Miscellaneous Operators in R:
R
# R program to illustrate # the use of Miscellaneous
operators mat <- matrix (1:4, nrow = 1, ncol = 4) print("Matrix elements using :
") print(mat) product = mat %*% t(mat) print("Product of
matrices") print(product,) cat ("does 1 exist in prod matrix :", "1" %in% product)
Output
[1] "Matrix elements using : " [,1] [,2] [,3] [,4] [1,] 1 2 3 4 [1] "Product of matrices" [,1]
[1,] 30 does 1 exist in prod matrix : FALSE

Decision Making in R Programming – if, if-else, if-else-if ladder, nested if-else, and
switch
Decision making is about deciding the order of execution of statements based on certain
conditions. In decision making programmer needs to provide some condition which is
evaluated by the program, along with it there also provided some statements which are
executed if the condition is true and optionally other statements if the condition is
evaluated to be false.
The decision making statement in R are as followed:
 if statement
 if-else statement
 if-else-if ladder
 nested if-else statement
 switch statement
if statement
Keyword if tells compiler that this is a decision control instruction and the condition
following the keyword if is always enclosed within a pair of parentheses. If the
condition is TRUE the statement gets executed and if condition is FALSE then
statement does not get executed.
Syntax:
if(condition is true){
execute this statement
}
Flow Chart:
Example:
r

# R program to illustrate
# if statement
a <- 76
b <- 67

# TRUE condition
if(a > b)
{
c <- a - b
print("condition a > b is TRUE")
print(paste("Difference between a, b is : ", c))
}

# FALSE condition
if(a < b)
{
c <- a - b
print("condition a < b is TRUE")
print(paste("Difference between a, b is : ", c))
}

Output:
[1] "condition a > b is TRUE"
[1] "Difference between a, b is : 9"
if-else statement
If-else, provides us with an optional else block which gets executed if the condition
for if block is false. If the condition provided to if block is true then the statement
within the if block gets executed, else the statement within the else block gets
executed.
Syntax:
if(condition is true) {
execute this statement
} else {
execute this statement
}
Flow Chart:

Example :
r

# R if-else statement Example


a <- 67
b <- 76
# This example will execute else block
if(a > b)
{
c <- a - b
print("condition a > b is TRUE")
print(paste("Difference between a, b is : ", c))
} else
{
c <- a - b
print("condition a > b is FALSE")
print(paste("Difference between a, b is : ", c))
}

Output:
[1] "condition a > b is FALSE"
[1] "Difference between a, b is : -9"
if-else-if ladder
It is similar to if-else statement, here the only difference is that an if statement is
attached to else. If the condition provided to if block is true then the statement
within the if block gets executed, else-if the another condition provided is checked
and if true then the statement within the block gets executed.
Syntax:
if(condition 1 is true) {
execute this statement
} else if(condition 2 is true) {
execute this statement
} else {
execute this statement
}
Flow Chart:
Example :
r

# R if-else-if ladder Example


a <- 67
b <- 76
c <- 99
if(a > b && b > c)
{
print("condition a > b > c is TRUE")
} else if(a < b && b > c)
{
print("condition a < b > c is TRUE")
} else if(a < b && b < c)
{
print("condition a < b < c is TRUE")
}

Output:
[1] "condition a < b < c is TRUE"
Nested if-else statement
When we have an if-else block as an statement within an if block or optionally
within an else block, then it is called as nested if else statement. When an if condition
is true then following child if condition is validated and if the condition is wrong else
statement is executed, this happens within parent if condition. If parent if condition
is false then else block is executed with also may contain child if else statement.
Syntax:
if(parent condition is true) {
if( child condition 1 is true) {
execute this statement
} else {
execute this statement
}
} else {
if(child condition 2 is true) {
execute this statement
} else {
execute this statement
}
}
Flow Chart:

Example:
r

# R Nested if else statement Example


a <- 10
b <- 11

if(a == 10)
{
if(b == 10)
{
print("a:10 b:10")
} else
{
print("a:10 b:11")
}
} else
{
if(a == 11)
{
print("a:11 b:10")
} else
{
print("a:11 b:11")
}
}

Output:
[1] "a:10 b:11"
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.
Syntax:
switch (expression, case1, case2, case3,…,case n )
Flow Chart :
Example:
r

# R switch statement example

# Expression in terms of the index value


x <- switch(
2, # Expression
"Geeks1", # case 1
"for", # case 2
"Geeks2" # case 3
)
print(x)

# Expression in terms of the string value


y <- switch(
"GfG3", # Expression
"GfG0"="Geeks1", # case 1
"GfG1"="for", # case 2
"GfG3"="Geeks2" # case 3
)
print(y)

z <- switch(
"GfG", # Expression
"GfG0"="Geeks1", # case 1
"GfG1"="for", # case 2
"GfG3"="Geeks2" # case 3
)
print(z)
print(z)
Output:
[1] "for"
[1] "Geeks2"
NULL
Loops in R (for, while, repeat)
A loop is a control statement that allows multiple executions of a statement or a set of
statements. The word ‘looping’ means cycling or iterating.
A loop asks a query, in the loop structure. If the answer to that query requires an action, it
will be executed. The same query is asked again and again until further action is taken.
Any time the query is asked in the loop, it is known as an iteration of the loop. There are
two components of a loop, the control statement, and the loop body. The control
statement controls the execution of statements depending on the condition and the loop
body consists of the set of statements to be executed.
In order to execute identical lines of code numerous times in a program, a programmer
can simply use a loop.
There are three types of loops in R programming:
 For Loop
 While Loop
 Repeat Loop
For Loop in R
It is a type of control statement that enables one to easily construct an R loop that has to
run statements or a set of statements multiple times. For R loop is commonly used to
iterate over items of a sequence. It is an entry-controlled loop, in this loop, the test
condition is tested first, then the body of the loop is executed, the loop body would not be
executed if the test condition is false.
R – For loop Syntax:
for (value in sequence)
{
statement
}
For Loop Flow Diagram:
Below are some programs to illustrate the use of for loop in R programming.
Example 1: Program to display numbers from 1 to 5 using for loop in R.
R

# R program to demonstrate the use of for loop

# using for loop


for (val in 1: 5)
{
# statement
print(val)
}

Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Here, for loop is iterated over a sequence having numbers from 1 to 5. In each iteration,
each item of the sequence is displayed.
R For-Loop on a List
R

# Create a list of numbers


my_list <- list(1, 2, 3, 4, 5)

# Loop through the list and print each element


for (i in seq_along(my_list)) {
current_element <- my_list[[i]]
print(paste("The current element is:", current_element))
}

Output
[1] "The current element is: 1"
[1] "The current element is: 2"
[1] "The current element is: 3"
[1] "The current element is: 4"
[1] "The current element is: 5"
While Loop in R
It is a type of control statement that will run a statement or a set of statements repeatedly
unless the given condition becomes false. It is also an entry-controlled loop, in this loop,
the test condition is tested first, then the body of the loop is executed, the loop body
would not be executed if the test condition is false.
R – While loop Syntax:
while ( condition )
{
statement
}
While loop Flow Diagram:
Below are some programs to illustrate the use of the while loop in R programming.
Example 1: Program to display numbers from 1 to 5 using a while loop in R.
R

# R program to demonstrate the use of while loop

val = 1

# using while loop


while (val <= 5)
{
# statements
print(val)
val = val + 1
}

Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Initially, the variable value is initialized to 1. In each iteration of the while loop the
condition is checked and the value of val is displayed and then it is incremented until it
becomes 5 and the condition becomes false, the loop is terminated.
Repeat Loop in R
It is a simple loop that will run the same statement or a group of statements repeatedly
until the stop condition has been encountered. Repeat loop does not have any condition to
terminate the loop, a programmer must specifically place a condition within the loop’s
body and use the declaration of a break statement to terminate this loop. If no condition is
present in the body of the repeat loop then it will iterate infinitely.
R – Repeat loop Syntax:
repeat
{
statement

if( condition )
{
break
}
}
Repeat loop Flow Diagram:

To terminate the repeat loop, we use a jump statement that is the break keyword. Below
are some programs to illustrate the use of repeat loops in R programming.
Example 1: Program to display numbers from 1 to 5 using a repeat loop in R.
R

# R program to demonstrate the use of repeat loop

val = 1
# using repeat loop
repeat
{
# statements
print(val)
val = val + 1

# checking stop condition


if(val > 5)
{
# using break statement
# to terminate the loop
break
}
}

Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
In the above program, the variable val is initialized to 1, then in each iteration of the
repeat loop the value of val is displayed and then it is incremented until it becomes
greater than 5. If the value of val becomes greater than 5 then a break statement is used to
terminate the loop.
Jump Statements in Loop
We use a jump statement in loops to terminate the loop at a particular iteration or to skip a
particular iteration in the loop. The two most commonly used jump statements in loops
are:
 Break Statement: The break keyword is a jump statement that is used to terminate
the loop at a particular iteration.
Example:
R

# R program to illustrate
# the use of break statement

# using for loop


# to iterate over a sequence
for (val in 1: 5)
{
# checking condition
if (val == 3)
{
# using break keyword
break
}

# displaying items in the sequence


print(val)
}

Output:
[1] 1
[1] 2
In the above program, if the value of val becomes 3 then the break statement will be
executed and the loop will terminate.
 Next Statement: The next keyword is a jump statement which is used to skip a
particular iteration in the loop.
Example:
R

# R program to illustrate
# the use of next statement

# using for loop


# to iterate over the sequence
for (val in 1: 5)
{
# checking condition
if (val == 3)
{
# using next keyword
next
}

# displaying items in the sequence


print(val)
}

Output:
[1] 1
[1] 2
[1] 4
[1] 5
In the above program, if the value of Val becomes 3 then the next statement will be
executed hence the current iteration of the loop will be skipped. So 3 is not displayed in
the output.
Functions in R Programming
A function accepts input arguments and produces the output by executing valid R
commands that are inside the function.
Functions are useful when you want to perform a certain task multiple times.
In R Programming Language when you are creating a function the function name and the
file in which you are creating the function need not be the same and you can have one or
more functions in R.
Creating a Function in R Programming
Functions are created in R by using the command function(). The general structure of the
function file is as follows:

Functions in R Programming
Note: In the above syntax f is the function name, this means that you are creating a
function with name f which takes certain arguments and executes the following
statements.
Parameters or Arguments in R Functions:
Parameters and arguments are same term in functions.
Parameters or arguments are the values passed into a function.
A function can have any number of arguments, they are separated by comma in
paranthesis.
Example:
R

# function to add 2 numbers


add_num <- function(a,b)
{
sum_result <- a+b
return(sum_result)
}
# calling add_num function
sum = add_num(35,34)
#printing result
print(sum)

Output
[1] 69
No. of Parameters:
Function should be called with right no. of parameters, neither less nor more or else it will
give error.
Default Value of Parameter:
Some functions have default values, and you can also give default value in your user-
defined functions. These values are used by functions if user doesn’t pass any parameter
value while calling a function.
Return Value:
You can use return() function if you want your function to return the result.
Calling a Function in R
After creating a Function, you have to call the function to use it.
Calling a function in R is very easy, you can call a function by writing it’s name and
passing possible parameters value.
Passing Arguments to Functions in R Programming Language
There are several ways you can pass the arguments to the function:
 Case 1: Generally in R, the arguments are passed to the function in the same order as
in the function definition.
 Case 2: If you do not want to follow any order what you can do is you can pass the
arguments using the names of the arguments in any order.
 Case 3: If the arguments are not passed the default values are used to execute the
function.
Now, let us see the examples for each of these cases in the following R code:
R

# A simple R program to demonstrate


# passing arguments to a function

Rectangle = function(length=5, width=4){


area = length * width
return(area)
}
# Case 1:
print(Rectangle(2, 3))

# Case 2:
print(Rectangle(width = 8, length = 4))

# Case 3:
print(Rectangle())

Output
[1] 6
[1] 32
[1] 20

Types of Function in R Language


1. Built-in Function: Built-in functions in R are pre-defined functions that are available
in R programming languages to perform common tasks or operations.
2. User-defined Function: R language allow us to write our own function.
Built-in Function in R Programming Language
Built-in Function are the functions that are already existing in R language and you just
need to call them to use.
Here we will use built-in functions like sum(), max() and min().
R

# Find sum of numbers 4 to 6.


print(sum(4:6))

# Find max of numbers 4 and 6.


print(max(4:6))
# Find min of numbers 4 and 6.
print(min(4:6))

Output
[1] 15
[1] 6
[1] 4

Other Built-in Functions in R:


Let’s look at the list of built-in R functions and their uses:

Functions Syntax

Mathematical Functions

abs() calculates a number’s absolute value.

sqrt() calculates a number’s square root.

round() rounds a number to the nearest integer.

calculates a number’s exponential


exp()
value

which calculates a number’s natural


log()
logarithm.

calculates a number’s cosine, sine, and


cos(), sin(), and tan()
tang.

Statistical Functions

A vector’s arithmetic mean is


mean()
determined by the mean() function.
Functions Syntax

A vector’s median value is determined


median()
by the median() function.

calculates the correlation between two


cor()
vectors.

calculates the variance of a vector and


var() calculates the standard deviation of a
vector.

User-defined Functions in R Programming Language


User-defined functions are the functions that are created by the user.
User defines the working, parameters, default parameter, etc. of that user-defined
function. They can be only used in that specific code.
Example
R

# A simple R function to check


# whether x is even or odd

evenOdd = function(x){
if(x %% 2 == 0)
return("even")
else
return("odd")
}

print(evenOdd(4))
print(evenOdd(3))

Output
[1]"even"
[1] "odd"
Nested Functions
There are two ways to create a nested function:
 Call a function within another function.
 Write a function within a function.

Example
Call a function within another function:

Nested_function <- function(x, y) {


a <- x + y
return(a)
}

Nested_function(Nested_function(2,2), Nested_function(3,3))
Example Explained
The function tells x to add y.
The first input Nested_function(2,2) is "x" of the main function.
The second input Nested_function(3,3) is "y" of the main function.
The output is therefore (2+2) + (3+3) = 10.
Example
Write a function within a function:
Outer_func <- function(x) {
Inner_func <- function(y) {
a <- x + y
return(a)
}
return (Inner_func)
}
output <- Outer_func(3) # To call the Outer_func
output(5)
Example Explained
You cannot directly call the function because the Inner_func has been defined (nested)
inside the Outer_func.
We need to call Outer_func first in order to call Inner_func as a second step.
We need to create a new variable called output and give it a value, which is 3 here.
We then print the output with the desired value of "y", which in this case is 5.
The output is therefore 8 (3 + 5).

Function scoping

It implies that variables that are defined inside a function are not accessible outside that function.
Try running the following code and see if you understand the results:

pow_two <- function(x) {


y <- x ^ 2
return(y)
}
pow_two(4)
y
x

y was defined inside the pow_two() function and therefore it is not accessible outside of that
function.

Recursive Functions
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.
Efficient way to install and load R packages
The most common method of installing and loading packages is using
the install.packages() and library() function respectively. Let us see a brief about these
functions –
 Install.packages() is used to install a required package in the R programming
language.
Syntax:
install.packages(“package_name”)
 library() is used to load a specific package in R programming language
Syntax:
library(package_name)
In the case where multiple packages have to installed and loaded these commands have to be
specified repetitively. Thus making the approach inefficient.
Example:
R

install.packages("ggplot2")
install.packages("dplyr")
install.packages("readxl")

library(ggplot2)
library(dplyr)
library(readxl)

Given below are ways by which this can be avoided.


The most efficient way to install the R packages is by installing multiple packages at a time
using. For installing multiple packages we need to use install.packages( ) function again but
this time we can pass the packages to be installed as a vector or a list with each package
separated by comma(,).
Syntax :
install.packages ( c(“package 1″ ,”package 2”, . . . . , “package n”) )
install.packages(“package1″,”package2”, . . . . , “package n”)
Example :
R

install.packages(c("ggplot2","dplyr","readxl"))

install.packages("ggplot2","dplyr","readxl")

Similarly, package can be loaded efficiently by one of the following ways.


Method 1: Using library()
In this, the packages to be loaded are passed to the function but as a list with each package
separated by a comma (,).
Syntax:
library(“package1”, “package2″, . . . . ,”package n”)
search() is used to look at the currently attached packages.

You might also like