0% found this document useful (0 votes)
3 views

IDS Unit-4

The document provides an overview of conditionals and control flow in R programming, detailing various types of operators such as arithmetic, relational, logical, assignment, and miscellaneous operators. It explains the use of conditional statements, including 'if', 'if-else', and 'switch' statements, along with examples to illustrate their functionality. The document emphasizes the importance of these constructs in making decisions based on Boolean conditions in programming.

Uploaded by

upender
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

IDS Unit-4

The document provides an overview of conditionals and control flow in R programming, detailing various types of operators such as arithmetic, relational, logical, assignment, and miscellaneous operators. It explains the use of conditional statements, including 'if', 'if-else', and 'switch' statements, along with examples to illustrate their functionality. The document emphasizes the importance of these constructs in making decisions based on Boolean conditions in programming.

Uploaded by

upender
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

UNIT-4

CONDITIONALS AND CONTROL FLOW


R – Operators:
 In computer programming, an operator is a symbol which represents an action. An operator is
a symbol which tells the compiler to perform specific logical or mathematical manipulations. R
programming is very rich in built-in operators.
 In R programming, there are different types of operator, and each operator performs a different
task. For data manipulation, there are some advance operators also such as model formula and
list indexing.
 An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. R language is rich in built-in operators and provides following types of operators.
Types of Operators:
We have the following types of operators in R programming:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Miscellaneous Operators
ARITHMETIC OPERATORS
These operators are used to carry out mathematical operations like addition and multiplication. Here is
a list of arithmetic operators available in R. Following table shows the arithmetic operators supported by
R language. The operators act on each element of the vector.
Operator Description Example
> v <- c(2, 5.5, 6)
+ Adds two vectors > t <- c(8, 3, 4)
> print(v+t)
[1] 10.0 8.5 10.0
> v <- c(2, 5.5, 6)
- Subtracts second vector > t <- c(8, 3, 4)
from the first > print(v-t)
[1] -6.0 2.5 2.0
> v <- c(2, 5.5, 6)
* Multiplies both vectors > t <- c(8, 3, 4)
> print(v*t)
[1] 16.0 16.5 24.0
Divide the first vector with > v <- c(2 ,5.5, 6)
/ the second > t <- c(8, 3, 4)
> print(v/t)
[1] 0.250000 1.833333 1.500000
Give the remainder from > v <- c(2, 5.5, 6)
%% division (Modulus) of the > t <- c(8, 3, 4)
first vector with the second > print(v%%t)
[1] 2.0 2.5 2.0
The result of division of first > v <- c(2, 5.5, 6)
%/% vector with second > t <- c(8, 3, 4)
(quotient) > print(v%/%t)
[1] 0 1 1
The first vector raised to the > v <- c(2, 5.5, 6)
^ exponent of second vector > t <- c(8, 3, 4)
> print(v^t)
[1] 256.000 166.375 1296.000

RELATIONAL OPERATORS
A relational operator is a symbol which defines some kind of relation between two entities. These include
numerical equalities and inequalities. Relational operators are used to compare between values. Here is
a list of relational operators available in R language.

Relational Operators in R
Operator Description
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to

RELATIONAL OPERATORS AND VECTORS


Each element of the first vector is compared with the corresponding element of the second vector. The
result of comparison is a Boolean value. Following table shows the relational operators supported by R
language.
Operator Description Example
Checks if each element of the first vector > v <- c(2, 5.5, 6, 9)
> is greater than the corresponding element > t <- c(8, 2.5, 14, 9)
of the second vector. > print(v>t)
[1] FALSE TRUE FALSE FALSE

Checks if each element of the first vector > v <- c(2, 5.5, 6, 9)
< is less than the corresponding element of > t <- c(8, 2.5, 14, 9)
the second vector. > print(v<t)
[1] TRUE FALSE TRUE FALSE
Checks if each element of the first vector > v <- c(2, 5.5, 6, 9)
== is equal to the corresponding element of > t <- c(8, 2.5, 14, 9)
the second vector. > print(v==t)
[1] FALSE FALSE FALSE TRUE
Checks if each element of the first vector > v <- c(2, 5.5, 6, 9)
<= is less than or equal to the corresponding > t <- c(8, 2.5, 14, 9)
element of the second vector. > print(v<=t)
[1] TRUE FALSE TRUE TRUE
Checks if each element of the first vector > v <- c(2, 5.5, 6, 9)
>= is greater than or equal to the > t <- c(8, 2.5, 14, 9)
corresponding element of the second > print(v>=t)
vector. [1] FALSE TRUE FALSE TRUE
Checks if each element of the first vector > v <- c(2, 5.5, 6, 9)
!= is unequal to the corresponding element of > t <- c(8, 2.5, 14, 9)
the second vector. > print(v!=t)
[1] TRUE TRUE TRUE FALSE

LOGICAL OPERATORS
The logical operators allow a program to make a decision on the basis of multiple conditions. In the
program, each operand is considered as a condition which can be evaluated to a TRUE or FALSE
value. The value of the conditions is used to determine the overall value of the op1 operator op2.
Logical operations 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. Logical operators are used to carry
out Boolean operations like AND, OR etc.
Here is a list of logical operators available in R language.
Logical Operators in R
Operator Description
& Element-wise Logical AND Operator
| Element-wise Logical OR operator
! NOT operator
&& Logical AND operator
|| Logical OR operator

LOGICAL OPERATORS AND VECTORS


 Logical operators are applicable to those vectors whose type is logical, numeric, or complex. Each
element of the first vector is compared with the corresponding element of the second vector. The
result of comparison is a Boolean value.
 Operators & and | perform element-wise operation producing result having length of the longer
operand. The logical operator && and || considers only the first element of the vectors and give a
vector of single element as output. Zero is considered FALSE and non-zero numbers are taken as
TRUE.
 Following table shows the logical operators supported by R language. It is applicable only to
vectors of type logical, numeric or complex. All numbers greater than 1 are considered as logical
value TRUE.

Operator Description Example


It is called Element-wise Logical AND > v <- c(3, 1, TRUE, 2+3i)
& operator. It combines each element of the > t <- c(4, 1, FALSE, 2+3i)
first vector with the corresponding element > print(v&t)
of the second vector and gives an output [1] TRUE TRUE FALSE TRUE
TRUE if both the elements are TRUE. Any
non-zero integer value is considered as a
TRUE value, be it complex or real number.
It is called Element-wise Logical OR > v <- c(3, 1, TRUE, 2+3i)
| operator. It combines each element of the > t <- c(4, 1, FALSE, 2+3i)
first vector with the corresponding element > print(v|t)
of the second vector and gives an output [1] TRUE TRUE TRUE TRUE
TRUE if one the elements is TRUE.
It is called Logical NOT operator. Takes > v <- c(3, 1, TRUE, 2+3i)
! each element of the vector and gives the > print(!v)
opposite logical value. [1] FALSE FALSE FALSE FALSE

Called Logical AND operator. Takes first > v <- c(3, 1, TRUE, 2+3i)
&& element of both the vectors and gives the > t <- c(4, 1, FALSE, 2+3i)
TRUE only if both are TRUE. > print( v && t)
[1] TRUE
Called Logical OR operator. Takes first > v <- c(3, 1, TRUE, 2+3i)
|| element of both the vectors and gives the > t <- c(4, 1, FALSE, 2+3i)
TRUE if one of them is TRUE. > print( v || t)
[1] TRUE

ASSIGNMENT OPERATORS
An assignment operator is used to assign a new value to a variable. In R, these operators are used to
assign values to vectors. There are the following types of assignment operators which are supported by
R:
Operator Description Example
> v1 <- c(3, 1, TRUE, 2+3i)
<− > v2 <<- c(3, 1, TRUE, 2+3i)
or These operators are known as > v3 = c(3, 1, TRUE, 2+3i)
= Left Assignment operators > print(v1)
[1] 3+0i 1+0i 1+0i 2+3i
or
> print(v2)
<<−
[1] 3+0i 1+0i 1+0i 2+3i
> print(v3)
[1] 3+0i 1+0i 1+0i 2+3i
> c(3, 1, TRUE, 2+3i) -> v1
-> > c(3, 1, TRUE, 2+3i) ->> v2
or These operators are known as > print(v1)
->> Right Assignment operators [1] 3+0i 1+0i 1+0i 2+3i
> print(v2)
[1] 3+0i 1+0i 1+0i 2+3i
MISCELLANEOUS OPERATORS
Miscellaneous operators are used for a special and specific purpose. These operators are not used for
general mathematical or logical computation. There are the following miscellaneous operators which are
supported in R
Operator Description Example
Colon operator. It creates the > v <- 2:8
: series of numbers in Sequence > print(v)
for a vector. [1] 2 3 4 5 6 7 8
> v1 <- 8
This operator is used to > v2 <- 12
%in% identify if an element belongs > t <- 1:10
to a vector. > print(v1 %in% t)
[1] TRUE
> print(v2 %in% t)
[1] FALSE
> M = matrix( c(2, 6, 5, 1, 10,4),
This operator is used to nrow = 2, ncol = 3, byrow = TR
%*% multiply a matrix with its UE)
transpose. > t = M %*% t(M)
> print(t)
[,1] [,2]
[1,] 65 82
[2,] 82 117

CONDITIONAL STATEMENTS (DECISION MAKING STATEMENTS)


 A conditional statement or a conditional expression is a programming construct where a decision
is made to execute some code based on a Boolean (true or false) condition.
 Decision making statements 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.
 A more commonly used term for conditional expression in programming is an 'if-else' condition.
In plain English, this is stated as 'if this test is true then do this operation; otherwise do this
different operation'. 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.
Sr.No. Statement & Description
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:
 The if statement consists of the Boolean expressions followed by one or more statements. The if
statement is the simplest decision-making statement which helps us to take a decision on the
basis of the condition.
 The if statement is a conditional programming statement which performs the function and
displays the information if it is proved true.
 The block of code inside the if statement will be executed only when the Boolean expression
evaluates to be true. If the statement evaluates false, then the code which is mentioned after the
condition will run.
 The syntax of if statement in R is as follows:
if(boolean_expression)
{
// If the boolean expression is true, then statement(s) will be executed.
}
Flow Diagram
Ex1: > x <- 24L
> if(is.integer(x))
{
print("x is an Integer")
}
[1] "x is an Integer"
Ex2: > x <- 100
> if(x > 10)
{
print(paste(x, "is greater than 10"))
}
[1] "100 is greater than 10"
Ex3: > x <- 24
> if(x%%2==0)
{
cat(x," is an even number")
}
24 is an even number
> if(x%%2!=0)
{
cat(x," is an odd number")
}
If-else statement:
 In the if statement, the inner code is executed when the condition is true. The code which is
outside the if block will be executed when the if condition is false.
 There is another type of decision-making statement known as the if-else statement. An if-else
statement is the if statement followed by an else statement. An if-else statement, else statement
will be executed when the Boolean expression will false. In simple words, if a Boolean
expression will have true value, then the if block gets executed otherwise, the else block will get
executed.
 R programming treats any non-zero and non-null values as true, and if the value is either zero or
null, then it treats them as false.
 The basic syntax of If-else statement
if(boolean_expression)
{
// statement(s) will be executed if the boolean expression is true.
}
else
{
// statement(s) will be executed if the boolean expression is false.
}
Flow Diagram

Ex: # check the number 5 is grater than 10 or nor.


> x=5
> if(x > 10)
{
print(paste(x, "is greater than 10"))
}
else
{
print(paste(x, "is less than 10"))
}
[1] "5 is less than 10"
Ex2: # check the number 100 is less than 20 or nor.
> a<- 100
> if(a<20)
{
# if the condition is true then print the following
cat("a is less than 20\n")
}
else
{
# if the condition is false then print the following
cat("a is not less than 20\n")
}
> cat("The value of a is", a)
a is not less than 20
The value of a is 100
Ex3: # check the element is present in list or not
> x <- c("Hardwork", "is", "the", "key", "of", "success")
> if("key" %in% x) {
print("key is found")
} else {
print("key is not found")
}
[1] "key is found"
else if statement:
This statement is also known as nested if-else statement. The if statement is followed by an optional e
lse if....else statement. This statement is used to test various condition in a single if......else if statem
ent. There are some key points which are necessary to keep in mind when we are using the if.....else i
f.....else statement. These points are as follows:
1. if statement can have either zero or one else statement and it must come after any else if's
statement.
2. if statement can have many else if's statement and they come before the else statement.
3. Once an else if statement succeeds, none of the remaining else if's or else's will be tested.
The basic syntax of If-else statement is as follows:
if (boolean_expression_1)
{
// This block executes when the boolean expression 1 is true.
}
else if ( boolean_expression_2)
{
// This block executes when the boolean expression 2 is true.
}
else if ( boolean_expression_3)
{
// This block executes when the boolean expression 3 is true.
}
else
{
// This block executes when none of the above condition is true.
}
Flow Diagram
Ex1: > age <- readline(prompt="Enter age: ")
Enter age: 25
> age <- as.integer(age)
> if(age<18)
{
print("You are child")
} else if(age>30) {
print("You are old guy")
} else {
print("You are adult")
}
[1] "You are adult"
Ex2: > marks=83;
> if(marks>75)
{
print("First class")
}else if(marks>65){
print("Second class")
}else if(marks>55){
print("Third class")
}else{
print("Fail")
}
[1] "First class"
Nested If Statements:
You can also have if statements inside if statements, this is called nested if statements.
Ex: > x <- 41
> if (x > 10)
{
print("Above ten")
if (x > 20)
{
print("and also above 20!")
} else
{
print("but not above 20.")
}
} else
{
print("below 10.")
}
[1] "Above ten"
[1] "and also above 20!"
AND: The & symbol (and) is a logical operator, and is used to combine conditional statements:
Example
> #Test if a is greater than b, AND if c is greater than a:
> a <- 200
> b <- 33
> c <- 500
> if (a > b & c > a){
print("Both conditions are true")
}
[1] "Both conditions are true"
OR: The | symbol (or) is a logical operator, and is used to combine conditional statements:
Example
> #Test if a is greater than b, or if c is greater than a:
> a <- 200
> b <- 33
> c <- 500
> if (a > b | c > a){
print("At least one of the conditions is true")
}
[1] "At least one of the conditions is true"

R - Switch Statement:
A switch statement is a selection control mechanism that allows the value of an expression to change the
control flow of program execution via map and search. The switch statement is used in place of long if
statements which compare a variable with several integral values. It is a multi-way branch statement
which provides an easy way to dispatch execution for different parts of code. This code is based on the
value of the expression.
This statement allows a variable to be tested for equality against a list of values. A switch statement is a
little bit complicated. To understand it, we have some key points which are as follows:
 If expression type is a character string, the string is matched to the listed cases.
 If there is more than one match, the first match element is used.
 No default case is available.
 If no case is matched, an unnamed case is used.
There are basically two ways in which one of the cases is selected:
1. Based on Index: If the cases are values like a character vector, and the expression is evaluated
to a number than the expression's result is used as an index to select the case.
2. Based on Matching Value: When the cases have both case value and output value like
["case_1"="value1"], then the expression value is matched against case values. If there is a match
with the case, the corresponding value is the output.
The basic syntax of If-else statement is as follows:
switch(expression, case1, case2, case3....)
Flow Diagram

Ex1: > x <- switch(3, "Shubham", "Nishka", "Arpitha", "Sumit")


> print(x)
[1] "Arpitha"
Ex2: > # Perform Mathematical calculation
> val1 = 6
> val2 = 7
> val3 = "Mul"
> result=switch(val3, "Add"=cat("Addition=", val1+val2),
"Sub"=cat("Substraction=", val1-val2),
"Mul"=cat("Multiplication=", val1*val2),
"div"=cat("Division=", val1/val2),
"Mod"=cat("Modulus=", val1%%val2),
"Pwr"=cat("Power=", val1^val2),
)
Multiplication= 42
Ex3: > # Perform Mathematical calculation
> val1 = 6
> val2 = 7
> val3 = "Hello"
> result=switch(val3, "Add"=cat("Addition=", val1+val2),
"Sub"=cat("Substraction=", val1-val2),
"Mul"=cat("Multiplication=", val1*val2),
"div"=cat("Division=", val1/val2),
"Mod"=cat("Modulus=", val1%%val2),
"Pwr"=cat("Power=",val1^val2),
print("default case is executed")
)
[1] "default case is executed"
ITERATIVE PROGRAMMING IN R
INTRODUCTION
 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.
 In R programming, we require a control structure to run a block of code multiple times.
 Programming languages provide various control structures that allow for more complicated
execution paths.
 Loops come in the class of the most fundamental and strong programming concepts.
 The word ‘looping’ means cycling or iterating.
 Loops are used to repeat the process until the expression (condition) is TRUE. R uses three
keywords for, while and repeat for looping purpose. Next and break, provide additional control
over the loop.
 The break statement exits the control from the innermost loop.
 The next statement immediately transfers control to return to the start of the loop and statement
after next is skipped.
 The value returned by a loop statement is always NULL and is returned invisibly.
 A loop is a control statement that statement allows us to execute a statement or group of
statements multiple times. R programming language provides the following kinds of loop to
handle looping requirements.
S.No Loop Type & Description
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.
3 for loop
Like a while statement, except that it tests the condition at the end of the loop body.

FOR LOOP IN R
 A for loop is the most popular control flow statement. A for loop is used to iterate a vector.
 It is a type of control statement that enables one to easily construct a loop that has to run
statements or a set of statements multiple times.
 For 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.
 The syntax of for loop in R:
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.
Ex1: Program to display numbers from 1 to 5 using for loop in R. R program to demonstrate the use of
for loop
> # using for loop
> for (val in 1: 5)
{
print(val)
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Ex2: Program to display first four letters using for loop in R. R program to demonstrate the use of for
loop
> # using for loop
> v <- LETTERS[1:4]
> for ( i in v) {
print(i)
}
[1] "A"
[1] "B"
[1] "C"
[1] "D"
Ex3: Program to display days of a week.
> # Assigning strings to the vector
> week <- c('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')
> # Using for loop to iterate over each string in the vector
> for (day in week)
{
# displaying each string in the vector
print(day)
}
[1] "Sunday"
[1] "Monday"
[1] "Tuesday"
[1] "Wednesday"
[1] "Thursday"
[1] "Friday"
[1] "Saturday"

WHILE LOOP IN R
 A while loop is a type of control flow statements which is used to run a statement or a set of
statements repeatedly. The while loop terminates when the value of the Boolean expression will
be false.
 It is also an entry-controlled loop. In while loop, firstly the condition will be checked and then
after the body of the statement will execute. the loop body of the statement would not be executed
if the test condition is false. In this statement, the condition will be checked n+1 time, rather than
n times.
 The basic syntax of while loop is as follows
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.
Ex1: Program to display numbers from 1 to 5 using while loop in R.
> val = 1
> # using while loop
> while (val <= 5)
{
# statements
print(val)
val = val + 1
}
[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.
Ex2: Program to calculate factorial of a number.
> # assigning value to the variable whose factorial will be calculated
> n <- 5
> # assigning the factorial variable and iteration variable to 1
> factorial <- 1
> i <- 1
> # using while loop
> while (i <= n)
{
# multiplying the factorial variable with the iteration variable
factorial = factorial * i
# incrementing the iteration variable
i=i+1
}
> # displaying the factorial
> print(factorial)
[1] 120
 Here, at first, the variable n is assigned to 5 whose factorial is going to be calculated, then variable
i and factorial are assigned to 1. i will be used for iterating over the loop, and factorial will be
used for calculating the factorial.
 In each iteration of the loop, the condition is checked i.e. i should be less than or equal to 5, and
after that factorial is multiplied with the value of i, then i is incremented.
 When i becomes 5, the loop is terminated and the factorial of 5 i.e. 120 is displayed beyond the
scope of the loop.
REPEAT LOOP
 It is a simple loop that will run the same statement or a group of statements repeatedly until the
stop condition has been encountered (break occurs). Be careful while using it because of the
infinite nature of the loop.
 Repeat loop does not have any condition to terminate the loop, a programmer must specifically
place a condition within the loop’s body and must use the break statement to terminate the loop.
If no condition is present in the body of the repeat loop then it will iterate infinitely.
 For exiting, we include a break statement with a user-defined condition. This property of the
loop makes it different from the other loops.
 A repeat loop constructs with the help of the repeat keyword in R. It is very easy to construct an
infinite loop in R.
 The basic syntax of the repeat loop is as follows:
repeat {
commands
if(condition) {
break
}
}
Flow Diagram:

1. First, we have to initialize our variables than it will enter into the Repeat loop.
2. This loop will execute the group of statements inside the loop.
3. After that, we have to use any expression inside the loop to exit.
4. It will check for the condition. It will execute a break statement to exit from the loop.
5. If the condition is true.
6. The statements inside the repeat loop will be executed again if the condition is false.
Ex1: Print sequence of numbers from 1 to n, when it reached to 5 stop the process.
> # assigning the val variable to 1
> val = 1
> repeat
{
print(val)
val = val + 1
if(val > 5)
{
break
}
}
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Ex2: R program to illustrate repeat loop
> v <- c("Hello","repeat","loop")
> cnt <- 1
> repeat {
print(v)
cnt <- cnt+1
if(cnt > 4) {
break
}
}
[1] "Hello" "repeat" "loop"
[1] "Hello" "repeat" "loop"
[1] "Hello" "repeat" "loop"
[1] "Hello" "repeat" "loop"
Ex3: R program to illustrate repeat loop
> i <- 0
> repeat
{
print("Welcome to R Programming!")
i=i+1
if (i > 5)
{
break
}
}
[1] "Welcome to R Programming!"
[1] "Welcome to R Programming!"
[1] "Welcome to R Programming!"
[1] "Welcome to R Programming!"
[1] "Welcome to R Programming!"
[1] "Welcome to R Programming!"
Jump Statements in Loop / 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. 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. 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
The basic syntax for creating a break statement in R is – break
Flow Diagram:

Ex: 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)
}
[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. 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.
The basic syntax for creating a next statement in R is next
Flow Diagram:

Ex: 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)
}
[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.
 As we can conclude from the above two programs the basic difference between the two jump
statements is that the break statement terminates the loop and the next statement skips a
particular iteration of the loop.
LOOP OVER A LIST
Looping over a list is just as easy and convenient as looping over a vector. There are again two different
approaches here:
> primes_list <- list(2, 3, 5, 7, 11, 13)
> # loop version 1
> for (p in primes_list) {
+ print(p)
+}
[1] 2
[1] 3
[1] 5
[1] 7
[1] 11
[1] 13
> # loop version 2
> for (i in 1:length(primes_list)) {
+ print(primes_list[[i]])
+}
[1] 2
[1] 3
[1] 5
[1] 7
[1] 11
[1] 13
Notice that you need double square brackets - [[ ]] - to select the list elements in loop version 2.

FUNCTIONS IN R
INTRODUCTION
 A set of statements which are organized together to perform a specific task is known as a function.
Or Functions are useful when we want to perform a certain task multiple number of times.
 A function accepts input arguments and produces the output by executing valid R commands that
are inside the function.
 R provides a series of built-in functions, and it allows the user to create their own functions i.e.
user-defined 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.
 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 function
definitions in a single R file.
WRITING A FUNCTION IN R
Functions are created in R by using the command function(). The general structure of the function file
is as follows:
func_name <- function(arg_1, arg_2, ...) {
Function body
}
Components of Functions: There are four components of function, which are as follows:
1. Function Name:
 The function name is the actual name of the function.
 In R, the function is stored as an object with its name.
2. Arguments:
 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.
3. Function Body:
 The function body contains a set of statements which defines what the function does.
4. Return value:
 It is the last expression in the function body which is to be evaluated.
 Function May or may not return the one or more output values.
Types of function in R:
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(), sum(), max(), min(), mean() and log()
etc. these functions are directly call in the program by users.
 Examples of built-in functions are
# Creating sequence of numbers from 32 to 46.
> print(seq(32,46))
[1] 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
# Finding the sum of numbers from 1 to 10.
> print(sum(1:10))
[1] 55
# Find max of number from 1 to 10.
> print(max(1:10))
[1] 10
# Find max of number from 1 to 10.
> print(min(1:10))
[1] 1
# Finding the mean of numbers from 1 to 5.
> mean(1:5)
[1] 3
# Finding log value of sequence of number from 44 to 55 both including incremented by 1
> x_vector<-seq(45,55, by = 1)
> x_vector
[1] 45 46 47 48 49 50 51 52 53 54 55
> log(x_vector)
[1] 3.806662 3.828641 3.850148 3.871201 3.891820 3.912023 3.931826 3.951244
3.970292 3.988984 4.007333
 R has an array of mathematical functions.
S.No Function Description Example
1 abs(x) Takes the absolute value of x > x<- -4
> print(abs(x))
[1] 4
2 log(x, base=y) Takes the logarithm of x with base y; if > x<-10
base is not specified, returns the natural > log(x, base=2)
logarithm [1] 3.321928
3 log(x) It returns natural logarithm of input x. > x<- 4
> print(log(x))
[1] 1.386294
4 log10(x) It returns common logarithm of input x. > x<- 4
> print(log10(x))
[1] 0.60206
5 exp(x) Returns the exponential of x > x<- 4
> print(exp(x))
[1] 54.59815
6 sqrt(x) Returns the square root of x > x<-4
> print(sqrt(x))
[1] 2
7 factorial(x) Returns the factorial of x (x!) > x<-4
> print(factorial(x))
[1] 24
8 ceiling(x) Returns the smallest integer which is > x<- 4.5
larger than or equal to x. > print(ceiling(x))
[1] 5
9 floor(x) Returns the largest integer, which is > x<- 2.5
smaller than or equal to x. > print(floor(x))
[1] 2
10 trunc(x) It returns the truncate value of input x. > x<- c(1.2,2.5,8.1)
> print(trunc(x))
[1] 1 2 8
11 round(x, It returns round value of input x. > x<- -4
digits=n) > print(abs(x))
[1] 4
12 cos(x), It returns cos(x), sin(x) value of input x. > x<- 4
sin(x), > cos(x)
tan(x) [1] -0.6536436
> sin(x)
[1] -0.7568025
> tan(x)
[1] 1.157821
 R has an array of Basic statistic functions
S.No Function Description Example
1 mean(x) Mean of x > x<- c(1:5)
> mean(x)
[1] 3
2 median(x) Median of x > x<- c(1:5)
> median(x)
[1] 3
3 var(x) Variance of x > x<- c(1:5)
> var(x)
[1] 2.5
4 sd(x) Standard deviation of x > x<- c(1:5)
> sd(x)
[1] 1.581139
5 quantile(x) The quartiles of x > x<- c(1:5)
0% 25% 50% 75% 100%
1 2 3 4 5
6 summary(x) Summary of x: mean, min, max > x<- c(1:5)
etc. > summary(x)
Min. 1stQu. Median
1 2 3
Mean 3rdQu. Max.
3 4 5
 R has an array of string functions.
S.No Function Description Example
1 substr(x, It is used to extract substrings > a <- "987654321"
start=n1,stop=n2) in a character vector. > substr(a, 3, 5)
[1] "765"
2 grep(pattern, x , It searches for pattern in x. > st1 <- c('abcd','bdcd','abcdabcd')
ignore.case=FALSE, > pattern<- '^abc'
fixed=FALSE) > print(grep(pattern, st1))
[1] 1 3
3 sub(pattern, It finds pattern in x and > st1<- "England is beautiful but no
replacement, x, replaces it with replacement the part of EU"
ignore.case = (new) text. > sub("England', "UK", st1)
FALSE, > sub("England", "UK", st1)
fixed=FALSE) [1] "UK is beautiful but no the
part of EU"
4 paste(..., sep="") It concatenates strings after > paste('one',2,'three',4,'five')
using sep string to separate [1] "one 2 three 4 five"
them.
5 strsplit(x, split) It splits the elements of > print(strsplit(a, ""))
character vector x at split [[1]]
point. [1] "S" "p" "l" "i" "t" " " "a" "
l" "l" " " "t" "h" "e" " " "c" "h
" "a" "r" "a" "c" "t" "e" "r"
6 tolower(x) It is used to convert the string > st1<- "shuBHAm"
into lower case. > print(tolower(st1))
[1] "shubham"
7 toupper(x) It is used to convert the string > st1<- "shuBHAm"
into upper case. > print(toupper(st1))
[1] "SHUBHAM"

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.
 Call a Function: To call a function, use the function name followed by parenthesis, like
my_function():
 Example for user-defined function
# Print a message using user-defined function
> my_function <- function() {
print("Hello World!")
}
> my_function()
[1] "Hello World!"
Arguments:
Information can be passed into functions as arguments. Arguments are the parameters provided to a
function to perform operations in a programming language. Arguments are specified after the function
name, inside the parentheses. We can add as many arguments as we want, just separate them with a
comma. There is no limit on the number of arguments in a function in R. The following example has a
function with one argument (fname). When the function is called, we pass along a first name, which is
used inside the function to print the full name:
> my_function <- function(fname) {
paste(fname, "Kumar")
}
> my_function("Uday")
[1] "Uday Kumar"
> my_function("Sandeep")
[1] "Sandeep Kumar"
> my_function("Ashok")
[1] "Ashok Kumar"
Adding Arguments in R: We can pass an argument to a function while calling the function by simply
giving the value as an argument inside the parenthesis. Below is an implementation of a function with
a single argument.
Ex: # check the given number is divisible by 5 or not.
> divisbleBy5 <- function(n){
if(n %% 5 == 0)
{
return("number is divisible by 5")
}
else
{
return("number is not divisible by 5")
}
}
> divisbleBy5(100)
[1] "number is divisible by 5"
Adding Multiple Arguments in R: A function in R programming can have multiple arguments too.
Below is an implementation of a function with multiple arguments.
Ex: # check the first number is divisible by second number or not.
> divisible <- function(a, b){
if(a %% b == 0)
{
return(paste(a, "is divisible by", b))
}
else
{
return(paste(a, "is not divisible by", b))
}
}
> divisible(7, 3)
[1] "7 is not divisible by 3"
Adding Default Value in R: Default value in a function is a value that is not required to specify each
time the function is called. If the value is passed by the user, then the user-defined value is used by the
function otherwise, the default value is used. Below is an implementation of function with default
value.
Ex: # check the first number is divisible by second number or not.
> divisible <- function(a, b = 3){
if(a %% b == 0)
{
return(paste(a, "is divisible by", b))
}
else
{
return(paste(a, "is not divisible by", b))
}
}
> divisible(10, 5)
[1] "10 is divisible by 5"
> divisible(12)
[1] "12 is divisible by 3"
Dots Argument: Dots argument (…) is also known as ellipsis which allows the function to take an
undefined number of arguments. It allows the function to take an arbitrary number of arguments. Below
is an example of a function with an arbitrary number of arguments.
Ex: > fun <- function(n, ...){
l <- list(n, ...)
paste(l, collapse = " ")
}
> fun(5, 1L, 6i, 15.2, TRUE)
[1] "5 1 0+6i 15.2 TRUE"
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.
Ex: # Creating a function to print squares of numbers in sequence.
> myfunction <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
> myfunction(10)
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36
[1] 49
[1] 64
[1] 81
[1] 100
Function calling with no argument: In R, we can call a function without an argument in the following
way
Ex: # Creating a function to print squares of numbers in sequence.
> myfunction <- function() {
for(i in 1:5) {
a <- i^2
print(a)
}
}
# Calling the function myfunction with no argument.
> myfunction()
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
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.
Ex: # Creating a function with arguments.
> myfunction <- function(x,y,z) {
result <- x * y + z
print(result)
}
# Calling the function by position of arguments.
> myfunction(11,13,9)
[1] 152
# Calling the function by names of the arguments.
> myfunction(x = 2, y = 5, z = 3)
[1] 13
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.
Ex: # Creating a function with arguments.
> myfunction <- function(x = 11, y = 24) {
result <- x * y
print(result)
}
# Calling the function without giving any argument.
> myfunction()
[1] 264
# Calling the function with giving new values of the argument.
> myfunction(4, 6)
[1] 24
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.
Ex: > Rectangle = function(length=5, width=4){
area = length * width
return(area)
}
# pass arguments values in same order
> print(Rectangle(2, 3))
[1] 6
# pass the arguments using the names of the arguments in any order.
> print(Rectangle(width = 8, length = 4))
[1] 32
# arguments are not passed the default values are used
> print(Rectangle())
[1] 20
Lazy evaluations of Functions in R Programming Language: In R the functions are executed in a
lazy fashion. When we say lazy what it means is if some arguments are missing the function is still
executed as long as the execution does not involve those arguments.
Ex: > Cal= function(a, b, c) {
result = a*b
return(result)
}
> print(Cal(5, 10))
[1] 50
Ex: > Cal= function(a, b, c){
result = a*b*c
return(result)
}
> print(Cal(5, 10))
Error in Cal(5, 10) : argument "c" is missing, with no default
Return Values: To let a function return a result, use the return() function:
Ex1: > my_function <- function(x) {
return (5 * x)
}
> print(my_function(3))
[1] 15
> print(my_function(5))
[1] 25
> print(my_function(9))
[1] 45
Ex2: # 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))
[1] "even"
> print(evenOdd(5))
[1] "odd"
Single Input Single Output: Now create a function in R that will take a single input and gives us a
single output. Following is an example to create a function that calculates the area of a circle which takes
in the arguments the radius. So, to create a function, name the function as “areaOfCircle” and the
arguments that are needed to be passed are the “radius” of the circle.
Ex: # A simple R function to calculate area of a circle
> areaOfCircle = function(radius){
area = pi*radius^2
return(area)
}
> print(areaOfCircle(2))
[1] 12.56637
Multiple Input Multiple Output: Now create a function in R Language that will take multiple inputs
and gives us multiple outputs using a list. The functions in R Language takes multiple input objects but
returned only one object as output, this is, however, not a limitation because you can create lists of all
the outputs which you want to create and once the list is created you can access them into the elements
of the list and get the answers which you want.
Ex: > Rectangle = function(length, width){
area = length * width
perimeter = 2 * (length + width)
result = list("Area" = area, "Perimeter" = perimeter)
return(result)
}
> resultList = Rectangle(2, 3)
> print(resultList["Area"])
$Area
[1] 6
> print(resultList["Perimeter"])
$Perimeter
[1] 10
Inline Functions in R: Sometimes creating an R script file, loading it, executing it is a lot of work when
you want to just create a very small function. So, what we can do in this kind of situation is an inline
function. To create an inline function, you have to use the function command with the argument x and
then the expression of the function.
Ex: > f = function(x) x*100
> print(f(4))
[1] 400

NESTED FUNCTIONS
A nested function or the enclosing function is a function that is defined within another function. In
simpler words, a nested function is a function in another function. There are two ways to create a nested
function in the R programming language:
1. Calling a function within another function we created.
2. Writing a function within another function.
Calling a function within another function: For this process, we have to create the function with two
or more required parameters. After that, we can call the function that we created whenever we want to
Ex: # creating a function with two parameters
> myFunction <- function(x, y) {
# passing a command to the function
a <- x * y
return(a)
}
# creating a nested function
> myFunction(myFunction(2,2), myFunction(3,3))
[1] 36
Code explanation:
 Line 2: We creatd a function with two parameter values, x and y.
 Line 4: The function we created tells x to multiply y and assign the output to a variable a.
 Line 5: We return the value of a.
 Line 9: We make the first input myFunction(2,2) represent the primary function’s x parameter.
Likewise, we make the second input myFunction(3,3) represent the y parameter of the main
function.
Hence, we get the following expected output: (2 * 2) * (3 * 3) = 36
Writing a function within another function: In this process, we can’t directly call the function because
there is an inner function defined inside an outer function. Therefore, we will call the external function
to call the function inside.
Ex: # creating an outer function
> outerFunction <- function(x) {
# creating an inner function
innerFunction <- function(y) {
# passing a command to the function
a <- x * y
return(a)
}
return (innerFunction)
}
# To call the outer function
> output <- outerFunction(3)
> output(5)
[1] 15
Code explanation:
 Line 2: We create an outer function, outerFunction, and pass a parameter value x to the function.
 Line 4: We create an inner function, innerFunction, and pass a parameter value y to the function.
 Line 6: We pass a command to the inner function, which tells x to multiply y and assign the
output to a variable a.
 Line 7: We return the value of a.
 Line 9: We return the innerFunction.
 Line 12: To call the outer function, we create a variable output and give it a value of 3.
 Line 13: We print the output with the desired value of 5 as the value of the y parameter.
Therefore, the output is: (3 * 5 = 15)

FUNCTION SCOPING
 The scope of a variable is nothing more than the place in the code where it is referenced and
visible.
 There are two basic concepts of scoping, lexical(static) scoping and is dynamic scoping.
 In R, there is a concept of free variables, which add some spice to the scoping.
 R uses lexical scoping, which says the values of such variables are searched for in the
environment in which the function was defined.
> f <- function(a, b) {
Z=2
(a * b) / z
}
> a<- f(5, 2)
>a
[1] 5
 In this function, you have two formal arguments, a and b.
 You have another variable, z, in the body of the function, which is a free variable.
 The scoping rules of the language define how value is assigned to free variables.
 R uses lexical scoping, which says the value for z is searched for in the environment where the
function was defined.
 ‘Z’ is called free variable
Note: Lexical scoping is also referred to as static scoping.
 With dynamic scoping, the variable is bound to the most recent value assigned to that variable.
 R provides some escape routes to bypass the shortcomings of lexical scoping. The <- operator is
called a variable assignment operator.
 Given the expression a <- 3.14, the value is assigned to the variable in the current
environment. If you already had an assignment for the variable before in the same
environment, this one will overwrite it.
 Variable assignments only update in the current environment, and they never create a new scope.
When R is looking for a value of a given variable, it will start searching from the bottom.
 This means the current environment(The top level environment available to us at the R
command prompt is the global environment called R_GlobalEnv . Global environment can
be referred to as . GlobalEnv in R codes as well. We can use the ls() function to show what
variables and functions are defined in the current environment.) is inspected first, then its
enclosing environment(The enclosing environment is the environment where the function
was created. Every function has one and only one enclosing environment). The search goes
until either the value is found or the empty environment is reached.
> a <- 3.14
> add <- function(x,y)
{
x*y/a
}
> add(10,11)
[1] 35.03185
 When the function is called, only the two arguments are passed. R tries to look up the a variable's
value and first looks at the scope of the function.
 Since it cannot be found there, it look for the value in the enclosing scope, where it finally finds
it. If you had not defined the a variable, it would give you the following error: Error in b(10,
11) : object 'a' not found, stating that the lookup has failed.
 This brings us to the concept of environment. Environments in R are basically mappings from
variables to values.
 Every function has a local environment and a reference to the enclosing environment.
 This helps scoping and lookup. You have the option to add, remove, or modify variable mappings
and can even change the reference to the enclosing environment.

RECURSION FUNCTIONS IN R
 Recursion, in the simplest terms, is a type of looping technique. It exploits the basic working of
functions 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
> rec_fac <- function(x){
if(x==0 || x==1)
{
return(1)
}
else
{
return(x*rec_fac(x-1))
}
}
> rec_fac(5)
[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 with argument value and
returned.
 This process continues until the first function call returns its output, giving us the final result.
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.
Note: we can define looping or iteration as the process where the same set of instructions is repeated
multiple times in a single call. In contrast, we can enumerate recursion as the process where the output
of one iteration from a function call becomes the input of the next in a separate function call

LOADING AN R PACKAGE
Packages: Packages in R Programming language are a set of R functions, compiled code, and sample
data. These are stored under a directory called “library” within the R environment. By default, R installs
a group of packages during installation. Once we start the R console, only the default packages are
available by default. Other packages that are already installed need to be loaded explicitly to be utilized
by the R program that’s getting to use them.
What are Repositories? : A repository is a place where packages are located and stored so you can
install packages from it. Organizations and Developers have a local repository, typically they are online
and accessible to everyone. Some of the most popular repositories for R packages are:
 CRAN: Comprehensive R Archive Network(CRAN) is the official repository, it is a network of
ftp and web servers maintained by the R community around the world. The R community
coordinates it, and for a package to be published in CRAN, the Package needs to pass several
tests to ensure that the package is following CRAN policies.
 Bioconductor: Bioconductor is a topic-specific repository, intended for open source software
for bioinformatics. Similar to CRAN, it has its own submission and review processes, and its
community is very active having several conferences and meetings per year in order to maintain
quality.
 Github: Github is the most popular repository for open source projects. It’s popular as it comes
from the unlimited space for open source, the integration with git, a version control software, and
its ease to share and collaborate with others.

1. Check Available R Packages: To check the available R Packages, we have to find the library
location in which R packages are contained. R provides .libPaths() function to find the library
locations.
> .libPaths()
[1] "C:/Users/RAPS-UPENDER/AppData/Local/R/win-library/4.4" "C:/Program Files/R/ R-4.4.1/
library"
.libPaths(): When the above code executes, it produces the following output, which may vary
depending on the local settings of our PCs & Laptops.
2. Getting the list of all the packages installed: R provides library() function, which allows us to
get the list of all the installed packages.
library(): When we execute the above function, it produces the following result, which may vary
depending on the local settings of our PCs or laptops. Packages in library C:/Users/RAPS-
UPENDER/AppData/Local/R/win-library/4.4
> library()

Like library() function, R provides search() function to get all packages currently loaded in the R
environment.
> search()
[1] ".GlobalEnv" "tools:rstudio" "package:stats" "package:graphics" "package:grDevices"
[6] "package:utils" "package:datasets" "package:methods" "Autoloads" "package:base"
Install a New Package:
 In R, there are two techniques to add new R packages. The first technique is installing package
directly from the CRAN directory, and the second one is to install it manually after downloading
the package to our local system.
Install directly from CRAN: The following command is used to get the packages directly from CRAN
webpage and install the package in the R environment. We may be prompted to choose the nearest mirror.
Choose the one appropriate to our location.
install.packages("Package Name")
The syntax of installing XML package is as follows:
> install.packages("XML")
Output

Install package manually: To install a package manually, we first have to download it from
https://cran.r-project.org/web/packages/available_packages_by_name.html
The required package will be saved as a .zip file in a suitable location in the local system.

Once the downloading has finished, we will use the following command:
install.packages(file_name_with_path, repos = NULL, type = "source")
Install the package named "XML"
install.packages("C:\Users\RAPS-UPENDER\Downloads\graphics\xml2_1.2.2.zip", repos =
NULL, type = "source")
Load Package to Library:
 We cannot use the package in our code until it will not be loaded into the current R environment.
 We also need to load a package which is already installed previously but not available in the
current environment.
 There is the following command to load a package:
library("package Name", lib.loc = "path to library")
Command to load the XML package
install.packages("C:\Users\RAPS-UPENDER\Downloads\graphics\xml2_1.2.2.zip", repos
= NULL, type = "source")
MATHEMATICAL FUNCTIONS IN R
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.No Operator Description Example
1 abs(x) Takes the absolute value of x > x<- -4
> print(abs(x))
[1] 4
2 log(x, base=y) Takes the logarithm of x with base y; if base > x<-10
is not specified, returns the natural logarithm > log(x, base=2)
[1] 3.321928
3 log(x) It returns natural logarithm of input x. > x<- 4
> print(log(x))
[1] 1.386294
4 log10(x) It returns common logarithm of input x. > x<- 4
> print(log10(x))
[1] 0.60206
5 exp(x) Returns the exponential of x > x<- 4
> print(exp(x))
[1] 54.59815
6 sqrt(x) Returns the square root of x > x<-4
> print(sqrt(x))
[1] 2
7 factorial(x) Returns the factorial of x (x!) > x<-4
> print(factorial(x))
[1] 24
8 ceiling(x) Returns the smallest integer which is larger > x<- 4.5
than or equal to x. > print(ceiling(x))
[1] 5
9 floor(x) Returns the largest integer, which is smaller > x<- 2.5
than or equal to x. > print(floor(x))
[1] 2
10 trunc(x) It returns the truncate value of input x. > x<- c(1.2,2.5,8.1)
> print(trunc(x))
[1] 1 2 8
11 round(x, It returns round value of input x. > x<- -4
digits=n) > print(abs(x))
[1] 4
12 cos(x), It returns cos(x), sin(x) and tan(x) value of > x<- 4
sin(x), input x. > cos(x)
tan(x) [1] -0.6536436
> sin(x)
[1] -0.7568025
> tan(x)
[1] 1.157821

You might also like