UNIT- IV
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 Functions in R.
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.
There are the following types of operators used in R:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Miscellaneous Operators
R Arithmetic Operators:
Arithmetic Operators are used to accomplish arithmetic
operations. They can be operated on the basic data types
Numericals, Integers, Complex Numbers. Vectors with
these basic data types can also participate in arithmetic
operations, during which the operation is performed on
one to one element basis.
An example for each of the arithmetic operator on Numerical values is
provided below.
r_op_arithmetic.R
# R Arithmetic Operators Example for integers
a <- 7.5
b <- 2
print ( a+b ) #addition
print ( a-b ) #subtraction
print ( a*b ) #multiplication
print ( a/b ) #Division
print ( a%%b ) #Reminder
print ( a%/%b ) #Quotient
print ( a^b ) #Power of
Output:
[1] 9.5
[1] 5.5
[1] 15
[1] 3.75
[1] 1.5
[1] 3
[1] 56.25
An example for each of the arithmetic operator on Vectors is provided
below.
r_op_arithmetic_vector.R
# R Operators - R Arithmetic Operators Example for vectors
a <- c(8, 9, 6)
b <- c(2, 4, 5)
print ( a+b ) #addition
print ( a-b ) #subtraction
print ( a*b ) #multiplication
print ( a/b ) #Division
print ( a%%b ) #Reminder
print ( a%/%b ) #Quotient
print ( a^b ) #Power of
Output:
[1] 10 13 11
[1] 6 5 1
[1] 16 36 30
[1] 4.00 2.25 1.20
[1] 0 1 1
[1] 4 2 1
[1] 64 6561 7776
R Relational Operators:
Relational Operators are those that find out relation between the two
operands provided to them. Following are the six relational
operations R programming language supports. The output is boolean
(TRUE or FALSE) for all of the Relational Operators in R
programming language.
An example for each of the relational operator on Numberical
values is provided below.
r_op_relational.R
# R Operators - R Relational Operators Example for Numbers
a <- 7.5
b <- 2
print ( a>b ) # greater than
print ( a==b ) # equal to
print ( a<=b ) # less than or equal to
print ( a>=b ) # greater than or equal to
print ( a!=b ) # not equal to
Output:
[1] TRUE
[1] FALSE
[1] FALSE
[1] TRUE
[1] TRUE
An example for each of the relational operator on Vectors is
provided below.
r_op_relational_vector.R
# R Operators - R Relational Operators Example for Numbers
a <- c(7.5, 3, 5)
b <- c(2, 7, 0)
print ( a<b ) # less than
print ( a>b ) # greater than
print ( a==b ) # equal to
print ( a<=b ) # less than or equal to
print ( a>=b ) # greater than or equal to
print ( a!=b ) # not equal to
Element-wise Comparisons:
a b a < b a > b a == b a <= b a >= b a != b
7.5 2 FALSE TRUE FALSE FALSE TRUE TRUE
3 7 TRUE FALSE FALSE TRUE FALSE TRUE
5 0 FALSE TRUE FALSE FALSE TRUE TRUE
Expected Output:
[1] FALSE TRUE FALSE
[1] TRUE FALSE TRUE
[1] FALSE FALSE FALSE
[1] FALSE TRUE FALSE
[1] TRUE FALSE TRUE
[1] TRUE TRUE TRUE
R Logical Operators:
Logical Operators in R programming language work
only for the basic data types logical, numeric and
complex and vectors of these basic data types.
An example for each of the logical operators on Numerical values is
provided below.
r_op_logical.R
# R Operators - R Logical Operators Example for basic logical elements
a <- 0 # logical FALSE
b <- 2 # logical TRUE
print ( a & b ) # logical AND element wise
print ( a | b ) # logical OR element wise
print ( !a ) # logical NOT element wise
print ( a && b ) # logical AND consolidated for all elements
print ( a || b ) # logical OR consolidated for all elements
Expected Output:
[1] FALSE
[1] TRUE
[1] TRUE
[1] FALSE
[1] TRUE
An example for each of the logical operators on Vectors is provided
below.
r_op_logical_vector.R
# R Operators - R Logical Operators Example for boolean vectors
a <- c(TRUE, TRUE, FALSE, FALSE)
b <- c(TRUE, FALSE, TRUE, FALSE)
print ( a & b ) # logical AND element wise
print ( a | b ) # logical OR element wise
print ( !a ) # logical NOT element wise
print ( a && b ) # logical AND consolidated for all elements
print ( a || b ) # logical OR consolidated for all elements
Expected Output:
[1] TRUE FALSE FALSE FALSE
[1] TRUE TRUE TRUE FALSE
[1] FALSE FALSE TRUE TRUE
[1] TRUE
[1] TRUE
Conditional Statements
A conditional expression or a conditional statement is a
programming construct where a decision is made to
execute some code based on a boolean (true or false)
condition.
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'.
The following are the different conditional
statements in R Language
•if statement
•if else statement
•else if ladder statement
•switch() statement
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.
}
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.
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 Chart:
Example
x <- 30L
if([Link](x)) {
print("X is an Integer")
}
When the above code is compiled and executed, it produces
the following result −
[1] "X is an Integer"
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.
}
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.
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 Chart:
Example
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.
else if ladder 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.
}
Flow Chart:
Example
x <- c("what","is","truth")
if("Truth" %in% x) {
print("Truth is found the first time")
} else if ("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"
Example:
R Program to find the biggest of three numbers
x <- [Link](readline(prompt = "Enter first number :"))
y <- [Link](readline(prompt = "Enter second number :"))
z <- [Link](readline(prompt = "Enter third number :"))
if (x > y && x > z) {
print(paste("Greatest is :", x))
} else if (y > z) {
print(paste("Greatest is :", y))
} else{
print(paste("Greatest is :", z))
}
OUTPUT:
Enter first number :2
Enter second number :22
Enter third number :4
[1] "Greatest is : 22"
switch statement:
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.)
Example
x <- switch( 3, "first", "second", "third", "fourth")
print(x)
When the above code is compiled and executed, it produces the following
result −
[1] "third"
Example
y = "18"
x = switch( y, "9"="Hello Arpita", "12"="Hello Vaishali", "18"="Hello
Nishka",
"21"="Hello Shubham")
print (x)
OUTPUT:
[1] Hello Nishka
Iterative Programming in R:
In R programming, we require a control structure to run
a block of code multiple times.
Loops come in the class of the most fundamental and
strong programming concepts.
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.
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.
There are three types of loop 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 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.
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
}
Example:
v <- LETTERS[1:4]
for (i in v) {
print(i)
}
When the above code is compiled and executed, it produces the
following result −
[1] "A"
[1] "B"
[1] "C"
[1] "D"
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
}
Example
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"
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:
Example:
primes_list <- list(2, 3, 5, 7, 11, 13)
# loop version 1
for (p in primes_list) {
print(p)
}
# loop version 2
for (i in 1:length(primes_list)) {
print(primes_list[[i]])
}
Notice that you need double square brackets - [[ ]] - to select the list elements in
loop version 2.
Output
[1] 2
[1] 3
[1] 5
[1] 7
[1] 11
[1] 13
[1] 2
[1] 3
[1] 5
[1] 7
[1] 11
[1] 13
Functions in R:
Introduction and writing a Function in R
• A function is a block of code which only runs when it
is called.
• You can pass data, known as parameters, into a
function.
• A function can return data as a result.
• 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
• Written to carry out a specified task.
• May or may not have arguments
• Contain a body in which our code is written.
• May or may not return one or more output values.
Creating a Function
To create a function, use the function() keyword:
Example
my_function <- function() { # create a function with the name
my_function
print("Hello World!")
}
Call a Function
To call a function, use the function name followed by parenthesis, like
my_function():
Example
my_function <- function() {
print("Hello World!")
}
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 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() etc.
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():
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as
you want, just separate them with a comma.
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:
Example
my_function <- function(fname) {
paste(fname, "Griffin")
}
my_function("Peter")
my_function("Lois")
• my_function("Stewie")
Explanationmy_function takes one argument:
[Link] function uses paste() to concatenate the first name with the
string "Griffin", separated by a space.
Output:
[1] "Peter Griffin„
[1] "Lois Griffin„
[1] "Stewie Griffin"
Parameters or Arguments?
The terms "parameter" and "argument" can be used for the
same thing: information that are passed into a
function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the
function definition.
An argument is the value that is sent to the function when it is
called.
Number of Arguments:
By default, a function must be called with the correct number of arguments.
Meaning that if your function
expects 2 arguments, you have to call the function with 2 arguments, not
more, and not less:
Example
This function expects 2 arguments, and gets 1 argument:
my_function <- function(fname, lname = "Griffin") {
paste(fname, lname)
}
my_function("Peter")
Output:
[1] "Peter Griffin"
Return Values
To let a function return a result, use the return() function:
Example
my_function <- function(x) {
return (5 * x)
}
print(my_function(3))
print(my_function(5))
print(my_function(9))
Output
[1] 15
[1] 25
[1] 45
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
Example:
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))
Step 1:
Define the functionmyFunction(x, y) multiplies x and y and returns the result.
Step 2:
Evaluate the inner function callsInside the nested call:
myFunction(2, 2) → 2 * 2 = 4
myFunction(3, 3) → 3 * 3 = 9
So the outer call becomes:
myFunction(4, 9)
Step 3:
Evaluate the outer function
myFunction(4, 9) → 4 * 9 = 36
Final Output
[1] 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.
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
The local variable declared in a block and its scope is limited to the block in
which it is declared
The global variables are not the members of any function scope or block and
these variables are available in
all the functions in a program.
Example:
lm <- function(x) { x * x }
print(lm)
In the above code x is local to the function itself
Example:
y<-10
function(x) { x * y }
In the above code, the variable x is local to the function and y is the global
variable
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)
• Explanation:
• The function tri_recursion() takes one argument k.
• If k > 0, it calls itself with k - 1 and adds k to the result.
• When k reaches 0, it returns 0 — this is the base case that
stops recursion.
• As recursion unwinds, print(result) displays the running
totals.
Output in R Console:
[1] 1
[1] 3
[1] 6
[1] 10
[1] 15
[1] 21
Loading an R Package:
Packages already included in the initial installation may not have
functions that you need. In R, you can easily install and load additional
packages provided by other users.
1. To install packages:
You can either use [Link]() function
[Link]("foreign") # install 'foreign' package
or click Tools > Install packages. Write the package name in the dialog,
then click install.
2. Once you install the package, you need to load it so that it becomes
available to use. Simply use library() function.
library(foreign) # load 'foreign' package
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: