Unit 2
Unit 2
Sr.N
Statement & Description
o.
if statement
1
An if statement consists of a Boolean expression followed by one or
more statements.
if...else statement
2
An if statement can be followed by an optional else statement,
which executes when the Boolean expression is false.
switch statement
3
A switch statement allows a variable to be tested for equality
against a list of values.
R - If Statement
An if statement consists of a Boolean expression followed by one or more
statements.
Syntax
The basic syntax for creating an if statement in R is −
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true.
}
If the Boolean expression evaluates to be true, then the block of code inside
the if statement will be executed. If Boolean expression evaluates to
be false, then the first set of code after the end of the if statement (after the
closing curly brace) will be executed.
Flow Diagram
Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.
Example
Live Demo
x <-30L
if(is.integer(x)){
print("X is an Integer")
}
When the above code is compiled and executed, it produces the following
result −
Syntax
The basic syntax for creating an if...else statement in R is −
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true.
} else {
// statement(s) will execute if the boolean expression is false.
}
If the Boolean expression evaluates to be true, then the if block of code will
be executed, otherwise else block of code will be executed.
Flow Diagram
Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.
Example
Live Demo
x <- c("what","is","truth")
if("Truth"%in% x){
print("Truth is found")
}else{
print("Truth is not found")
}
When the above code is compiled and executed, it produces the following
result −
Syntax
The basic syntax for creating an if...else if...else statement in R is −
if(boolean_expression 1) {
// Executes when the boolean expression 1 is true.
} else if( boolean_expression 2) {
// Executes when the boolean expression 2 is true.
} else if( boolean_expression 3) {
// Executes when the boolean expression 3 is true.
} else {
// executes when none of the above condition is true.
}
Example
Live Demo
x <- c("what","is","truth")
if("Truth"%in% x){
print("Truth is found the first time")
}elseif("truth"%in% x){
print("truth is found the second time")
}else{
print("No truth found")
}
When the above code is compiled and executed, it produces the following
result −
R - Switch Statement
switch statement
In this switch function expression is matched to list of cases. If a match is
found then it prints that case’s value. No default case is available here. If
no case is matched it outputs NULL as shown in example.
Syntax
Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.
Example
Live Demo
x <-switch(
3,
"first",
"second",
"third",
"fourth"
)
print(x)
When the above code is compiled and executed, it produces the following
result −
[1] "third"
R - Loops
There may be a situation when you need to execute a block of code several
number of times. In general, statements are executed sequentially. The first
statement in a function is executed first, followed by the second, and so on.
Sr.N
Loop Type & Description
o.
repeat loop
1
Executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable.
while loop
2
Repeats a statement or group of statements while a given condition is
true. It tests the condition before executing the loop body.
for loop
3
Like a while statement, except that it tests the condition at the end of
the loop body.
Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that
scope are destroyed.
R supports the following control statements. Click the following links to check
their detail.
Sr.N
Control Statement & Description
o.
break statement
1
Terminates the loop statement and transfers execution to the
statement immediately following the loop.
Next statement
2
The next statement simulates the behavior of R switch.
Repeat loop
The Repeat loop executes the same code again and again until a stop
condition is met.
Syntax
repeat {
commands
if(condition) {
break
}
}
Flow Diagram
Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.
Example
Live Demo
v <- c("Hello","loop")
cnt<-2
repeat {
print(v)
cnt<- cnt+1
if(cnt>5){
break
}
}
When the above code is compiled and executed, it produces the following
result −
R - While Loop
The While loop executes the same code again and again until a stop
condition is met.
Syntax
while (test_expression) {
statement
}
Flow Diagram
Here key point of the while loop is that the loop might not ever run. When
the condition is tested and the result is false, the loop body will be skipped
and the first statement after the while loop will be executed.
Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.
Example
Live Demo
v <-c("Hello","while loop")
cnt<-2
while(cnt<7){
print(v)
cnt=cnt+1
}
When the above code is compiled and executed, it produces the following
result −
Syntax
The basic syntax for creating a for loop statement in R is −
for (value in vector) {
statements
}
Flow Diagram
R’s for loops are particularly flexible in that they are not limited to integers,
or even numbers in the input. We can pass character vectors, logical vectors,
lists or expressions.
Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.
Example
Live Demo
v <-LETTERS[1:4]
for(iin v){
print(i)
}
When the above code is compiled and executed, it produces the following
result −
[1] "A"
[1] "B"
[1] "C"
[1] "D"
R - Break Statement
The break statement in R programming language has the following two
usages −
Syntax
break
Flow Diagram
Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.
Example
Live Demo
v <- c("Hello","loop")
cnt<-2
repeat {
print(v)
cnt<-cnt+1
if(cnt>5){
break
}
}
When the above code is compiled and executed, it produces the following
result −
R - Next Statement
The next statement in R programming language is useful when we want to
skip the current iteration of a loop without terminating it. On encountering
next, the R parser skips further evaluation and starts next iteration of the
loop.
Syntax
next
Flow Diagram
Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.
Example
Live Demo
v <-LETTERS[1:6]
for(iin v){
if(i=="D"){
next
}
print(i)
}
When the above code is compiled and executed, it produces the following
result −
[1] "A"
[1] "B"
[1] "C"
[1] "E"
[1] "F"
R Functions
A set of statements which are organized together to perform a specific task is known as a
function. R provides a series of in-built functions, and it allows the user to create their own
functions. Functions are used to perform tasks in the modular approach.
Functions are used to avoid repeating the same task and to reduce complexity. To understand
and maintain our code, we logically break it into smaller parts using the function. A function
should be
1. Written to carry out a specified task.
2. May or may not have arguments
3. Contain a body in which our code is written.
4. May or may not return one or more output values.
"An R function is created by using the keyword function." There is the following syntax
of R function:
Components of Functions
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
Function Body
The function body contains a set of statements which defines what the function does.
Return value
It is the last expression in the function body which is to be evaluated.
Function Types
Similar to the other languages, R also has two types of function, i.e. Built-in
Function and User-defined Function. In R, there are lots of built-in functions which we can
directly call in the program without defining them. R also allows us to create our own
functions.
Built-in function
The functions which are already created or defined in the programming framework are
known as built-in functions. User doesn't need to create these types of functions, and these
functions are built into an application. End-users can access these functions by simply calling
it. R have different types of built-in functions such as seq(), mean(), max(), and sum(x) etc.
Output:
User-defined function
R allows us to create our own function in our program. A user defines a user-define function
to fulfill the requirement of user. Once these functions are created, we can use these functions
like in-built function.
Output:
ADVERTISEMENT
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.
Output:
Function calling with Argument Values
We can supply the arguments to a function call in the same sequence as defined in the
function or can supply in a different sequence but assigned them to the names of the
arguments.
Output:
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.
Output:
R Built-in Functions
The functions which are already created or defined in the programming framework are
known as a built-in function. R has a rich set of functions that can be used to perform almost
every task for the user. These built-in functions are divided into the following categories
based on their functionality.
Math Functions
String Function
R provides various string functions to perform tasks. These string functions allow us to
extract sub string from string, search pattern etc. There are the following string functions in
R:
R provides various statistical probability functions to perform statistical task. These statistical
functions are very helpful to find normal density, normal quantile and many more calculation.
In R, there are following functions which are used:
1. dnorm(x, m=0, sd=1, It is used to find the height of a <- seq(-7, 7, by=0.1)
log=False) the probability distribution at b <- dnorm(a, mean=2.5,
each point to a given mean and sd=0.5)
standard deviation png(file="dnorm.png")
plot(x,y)
dev.off()
2. pnorm(q, m=0, sd=1, it is used to find the probability a <- seq(-7, 7, by=0.2)
lower.tail=TRUE, of a normally distributed b <- dnorm(a, mean=2.5, sd=2)
log.p=FALSE) random numbers which are less png(file="pnorm.png")
than the value of a given plot(x,y)
number. dev.off()
12. dunif(x, min=0, max=1) This function provide dunif(x, min=0, max=1,
information about the uniform log=FALSE)
distribution on the interval
from min to max. It gives the
density.
13. punif(q, min=0, max=1) It gives the distributed function punif(q, min=0, max=1,
lower.tail=TRUE,
log.p=FALSE)
14. qunif(p, min=0, max=1) It gives the quantile function. qunif(p, min=0, max=1,
lower.tail=TRUE,
log.p=FALSE)
15. runif(x, min=0, max=1) It generates random deviates. runif(x, min=0, max=1)
Apart from the functions mentioned above, there are some other useful functions which helps
for statistical purpose. There are the following functions:
S. Function Description Example
No
A quick definition
Lazy evaluation is a programming strategy that allows a symbol to be evaluated only when
needed. In other words, a symbol can be defined (e.g in a function), and it will only be
evaluated when it is needed (and that moment can be never). This is why you can do:
{
a *10
plop(4)
## [1] 40
Here,
b
is defined as a function argument, but never evaluated. So no error. This strategy is called
“lazy” as it does “the strict minimum” of evaluation (remember that evaluation is looking for
the value of a symbol).
plop(a = 4, b = non_existing_variable)
## [1] 40
As
b
is never evaluated, we don’t have any problem, R never tries to look for the value of
non_existing_variable
.
if(TRUE){
12
}else{
no_variable
}
## [1] 12
if(FALSE){
no_variable
}else{
12
}
## [1] 12
if(TRUE||no_variable){
12
## [1] 12
Why lazy eval
Lazy evaluation is not R-restricted: it is also found in other languages (mainly functional
languages). Its opposite is strict/eager evaluation, which is the default in most programming
languages.
Lazy evaluation is implemented in R as it allows a program to be more efficient when used
interactively: only the necessary symbols are evaluated, that is to say that only the
needed objects will be loaded in memory and/or looked for. The downside being that it
can make a program less predictable, as you are never 100% sure a symbol will be evaluated
(but this is for more advanced use-cases).
It’s a typical mechanism for functional language, as it allows functions to be defined without
any values in it. That means that you can create this object without a and b having a value.
a+b
}
The expression given as function arguments are not evaluated before the function is called.
Instead, the expressions are packaged together with the environment in which they should be
evaluated and it is this package that is passed to the function. Evaluation only takes place
when the argument is required.
R Functions
In simple terms, a function is a block of statements that can be used repeatedly in a program.
R provides many built-in functions and allows programmers to define their own functions.
Syntax
Lazy Evaluation
R functions perform lazy evaluation that dramatically extends the expressive power of
functions. It is the technique of not evaluating arguments unless and until they are needed in
the function.
myfunc<- function(x, y) {
if(!x){
return(y)
}
else{
return(x)
}
}
R - Functions
A function is a set of statements organized together to perform a specific task. R has a large
number of in-built functions and the user can create their own functions.
In R, a function is an object so the R interpreter is able to pass control to the function, along
with arguments that may be necessary for the function to accomplish the actions.
The function in turn performs its task and returns control to the interpreter as well as any
result which may be stored in other objects.
Function Definition
An R function is created by using the keyword function. The basic syntax of an R function
definition is as follows −
function_name<- function(arg_1, arg_2, ...) {
Function body
}
Function Components
[1] 32 33 34 35 36 37 38 39 40 41 42 43 44
[1] 53.5
[1] 1526
User-defined Function
We can create user-defined functions in R. They are specific to what a user wants and once
created they can be used like the built-in functions. Below is an example of how a function is
created and used.
Calling a Function
# Create a function to print squares of numbers in sequence.
new.function<-function(a){
for(iin1:a){
b <- i^2
print(b)
}
}
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36
Calling a Function without an Argument
# Create a function without an argument.
new.function<-function(){
for(iin1:5){
print(i^2)
}
}
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
Calling a Function with Argument Values (by position and by name)
The arguments to a function call can be supplied in the same sequence as defined in the
function or they can be supplied in a different sequence but assigned to the names of the
arguments.
[1] 26
[1] 58
We can define the value of the arguments in the function definition and call the function
without supplying any argument to get the default result. But we can also call such functions
by supplying new values of the argument and get non default result.
[1] 18
[1] 45
Lazy Evaluation of Function
Arguments to functions are evaluated lazily, which means so they are evaluated only when
needed by the function body.
[1] 36
[1] 6
Error in print(b) : argument "b" is missing, with no default
In this article, you will learn to return a value from a function in R. You'll also learn to use
functions without the return function.
Many times, we will require our functions to do some processing and return the result. This is
accomplished with the return() function in R.
Syntax of return()
The syntax of the return() function is:
return(expression)
Here, expression is evaluated, and its value is stored as the result of the function.
The value specified in the return() statement is passed as the output of the function.
Example of return()
Let us look at an example which will return whether a given number is positive, negative or
zero.
check(1)
check(-10)
check(0)
Output
[1] "Positive"
[1] "Negative"
[1] "Zero"
Multiple Returns
The return() function can return only a single object. If we want to return multiple values in
R, we can use a list (or other objects) and return it.
Following is an example:
multi_return<- function() {
my_list<- list("color" = "red", "size" = 20, "shape" = "round")
return(my_list)
}
# call function multi_return() and assign the result to variable a
a <- multi_return()
a$color
a$size
a$shape
Output
[1] "red"
[1] 20
[1]"round"
Here, the function multi_return() creates a list object my_list, assigns some values to its
elements, and then returns the entire list as the output of the function.
The list contains three elements: "color" with the value "red", "size" with the value 20,
and "shape" with the value "round".
The multi_return() function is called and its result is assigned to the variable a.
Here,
a$color - accesses the value of the "color" element
a$size - accesses the value of the "size" element
a$shape - accesses the value of the "shape" element
R Functions
In simple terms, a function is a block of statements that can be used repeatedly in a program.
R provides many built-in functions and allows programmers to define their own functions.
Syntax
Recursive Function in R:
Recursion is when the function calls itself. This forms a loop, where every time the
function is called, it calls itself again and again and this technique is known as recursion.
Since the loops increase the memory we use the recursion. The recursive function uses the
concept of recursion to perform iterative tasks they call themselves, again and again, which
acts as a loop. These kinds of functions need a stopping condition so that they can stop
looping continuously. Recursive functions call themselves. They break down the problem
into smaller components. The function() calls itself within the original function() on each of
the smaller components. After this, the results will be put together to solve the original
problem.
Example: Factorial using Recursion in R
R
rec_fac<- function(x){
if(x==0 || x==1)
{
return(1)
else
return(x*rec_fac(x-1))
rec_fac(5)
Output:
[1] 120
Here, rec_fac(5) calls rec_fac(4), which then calls rec_fac(3), and so on until the input
argument x, has reached 1. The function returns 1 and is destroyed. The return value is
multiplied by the argument value and returned. This process continues until the first
function call returns its output, giving us the final result.
Example: Sum of Series Using Recursion
Recursion in R is most useful for finding the sum of self-repeating series. In this example,
we will find the sum of squares of a given series of numbers. Sum = 1 2+22+…+N2
Example:
R
sum_series<- function(vec){
if(length(vec)<=1)
return(vec^2)
else
return(vec[1]^2+sum_series(vec[-1]))
}
}
sum_series(series)
Output:
[1] 385
R
sum_n<- function(n) {
if (n == 1) {
return(1)
} else{
return(n + sum_n(n-1))
sum_n(5)
Output:
[1] 15
In this example, the sum_n function recursively increases n until it reaches 1, which is the
base case of the recursion, by adding the current value of n to the sum of the first n-1
values.
R
exp_n<- function(base, n) {
if (n == 0) {
return(1)
} else{
exp_n(4, 5)
Output:
[1] 1024
In this example, the base case of the recursion is represented by the exp_n function, which
recursively multiplies the base by itself n times until n equals 0.
Types of Recursion in R
1. Direct Recursion: The recursion that is direct involves a function calling itself directly.
This kind of recursion is the easiest to understand.
3. Mutual Recursion: Multiple functions that call each other repeatedly make up mutual
recursion. To complete a task, each function depends on the others.
4. Nested Recursion: Nested recursion happens when one recursive function calls another
recursively while passing the output of the first call as an argument. The arguments of
one recursion are nested inside of this one.
5. Structural Recursion: Recursion that is based on the structure of the data is known as
structural recursion. It entails segmenting a complicated data structure into smaller pieces
and processing each piece separately.
Recursion
R also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the
benefit of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never
terminates, or one that uses excess amounts of memory or processor power. However, when written correctly,
recursion can be a very efficient and mathematically-elegant approach to programming.
In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use the k variable as
the data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0
(i.e. when it is 0).
To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and
modifying it.
Example
tri_recursion<- function(k) {
if (k > 0) {
result <- k + tri_recursion(k - 1)
print(result)
} else {
result = 0
return(result)
}
}
tri_recursion(6)
output
[1] 1
[1] 3
[1] 6
[1] 10
[1] 15
[1] 21