0% found this document useful (0 votes)
7 views20 pages

R Programming Unit II Notes

The document provides an overview of control statements and functions in R programming, including decision-making structures such as if, if...else, and switch statements. It also covers iterative statements like repeat, while, and for loops, along with loop control statements like break and next. Additionally, it discusses formal and actual arguments, named arguments, global and local variables, lazy evaluation, and recursive functions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views20 pages

R Programming Unit II Notes

The document provides an overview of control statements and functions in R programming, including decision-making structures such as if, if...else, and switch statements. It also covers iterative statements like repeat, while, and for loops, along with loop control statements like break and next. Additionally, it discusses formal and actual arguments, named arguments, global and local variables, lazy evaluation, and recursive functions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.

D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


R Programming

Unit II Control Statements and Functions

Control Statements: -

Decision making structures require the programmer to specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the condition
is determined to be false.

R provides the following types of decision-making statements.

[Link]. 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.

1) 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.
}
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


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: -

Example: -

x <- 30L
if([Link](x)) {
print("X is an Integer")
}

Output: -

[1] "X is an Integer"

2) if else statement: -

An if statement can be followed by an optional else statement which executes when the
boolean expression is false.
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


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:_

Example:-
Live Demo

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

if("Truth" %in% x) {
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


print("Truth is found")
} else
{
print("Truth is not found")
}

Output: -

[1] "Truth is not found"


3) Switch Statement: -

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.)
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


Flow Diagram:-

Example:-
Live Demo

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

Output: -

[1] "third"

Iterative Statements/ Looping Statements: -

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.
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


Programming languages provide various control structures that allow for more complicated
execution paths.A loop statement allows us to execute a statement or group of statements multiple
times and the following is the general form of a loop statement in most of the programming
languages −

R programming language provides the following kinds of loop to handle looping requirements.

[Link]. 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.

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

1) repeat loop:-

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

Syntax:-

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

repeat {
commands
if(condition) {
break
}
}
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


Flow Diagram:-

Example:-
Live Demo

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

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

if(cnt > 5) {
break
}
}

Output: -

[1] "Hello" "loop"


[1] "Hello" "loop"
[1] "Hello" "loop"
[1] "Hello" "loop"
Kickstart Your C
2) while loop:-

The While loop executes the same code again and again until a stop condition is met.
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


Syntax:-

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

while (test_expression)
{
statement
}

Flow Diagram:-

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

Example: -
Live Demo

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


cnt <- 2

while (cnt < 7) {


print(v)
cnt = cnt + 1
}
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


Output: -

[1] "Hello" "while loop"


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

3) for loop: -

A For loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.

Syntax: -

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

for (value in vector)


{
statements
}
Flow Diagram:-

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

Example:-
Live Demo

v <- LETTERS [1:4]


for ( i in v) {
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


print(i)
}

Output: -

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

Loop Control Statements: -

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

R supports the following control statements.

[Link]. Control Statement & Description

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.

1) break statement: -

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

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

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

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


Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


break

Flow Diagram:-

Example: -
o

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

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

if(cnt > 5) {
break
}
}

Output: -

[1] "Hello" "loop"


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

2) next statement: -
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


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

Syntax:-

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

next

Flow Diagram:-

Example:-
Live Demo

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

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

Output: -

[1] "A"
[1] "B"
[1] "C"
[1] "E"
[1] "F"
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


Formal and Actual Arguments: -

Example: -

>pow(8, 2)
[1] "8 raised to the power 2 is 64"
>pow(2, 8)
"2 raised to the power 8 is 256”

 Here, the arguments used in the function declaration (x and y) are called
formal arguments and those used while calling the function are called actual
arguments.
 In the above function calls, the argument matching of formal argument to the
actual arguments takes place in positional order.
 This means that, in the call pow(8,2), the formal arguments x and y are
assigned 8 and 2 respectively

Named Arguments: -
Named Arguments We can also call the function using named arguments.
When calling a function in this way, the order of the actual arguments doesn’t matter.
Example: -
>pow(8, 2) [1]
"8 raised to the power 2 is 64"
>pow(x = 8, y = 2) [1]
"8 raised to the power 2 is 64"
>pow(y = 2, x = 8) [1]
"8 raised to the power 2 is 64"

Global and Local Variables: -

1) Global Variables: -

Variables that are created outside of a function are known as global variables.
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


Global variables can be used by everyone, both inside of functions and outside.

Example: -

Create a variable outside of a function and use it inside the function:

txt <- "awesome"


my_function <- function() {
paste("R is", txt)
}
my_function()

2) Local Variables: -

Variables defined within a function or block are said to be local to those functions.
 Local variables do not exist outside the block in which they are declared, i.e.
they can not be accessed or used outside that block.
 Declaring local variables: Local variables are declared inside a block
 .
Example: -

func = function()
{
age = 18
}

print(age)

Argument and Lazy evaluation of functions: -

Lazy evaluation is an evaluation strategy which holds the evaluation of an expression until its
value is needed. It avoids repeated evaluation. Haskell is a good example of such a functional
programming language whose fundamentals are based on Lazy Evaluation.
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


Lazy evaluation is used in Unix map functions to improve their performance by loading only
required pages from the disk. No memory will be allocated for the remaining pages.

Lazy Evaluation – Advantages: -


 It allows the language runtime to discard sub-expressions that are not directly linked to the
final result of the expression.
 It reduces the time complexity of an algorithm by discarding the temporary computations
and conditionals.
 It allows the programmer to access components of data structures out-of-order after
initializing them, as long as they are free from any circular dependencies.
 It is best suited for loading data which will be infrequently accessed.
Lazy Evaluation – Drawbacks: -
 It forces the language runtime to hold the evaluation of sub-expressions until it is required
in the final result by creating thunks (delayed objects).
 Sometimes it increases space complexity of an algorithm.
 It is very difficult to find its performance because it contains thunks of expressions before
their execution.

Example: -

r = range(10)
print(r)
range(0, 10)
print(r[3])

Output: -

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3

Recursive Function: -

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.
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


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)

Output: -

[1] 120

R Strings: -

Any value written within a pair of single quote or double quotes in R is treated as a
string. Internally R stores every string within double quotes, even when you create them
with single quote.

Rules Applied in String Construction:-

 The quotes at the beginning and end of a string should be both double quotes or
both single quote. They can not be mixed.
 Double quotes can be inserted into a string starting and ending with single quote.
 Single quote can be inserted into a string starting and ending with double quotes.
 Double quotes can not be inserted into a string starting and ending with double
quotes.
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


 Single quote can not be inserted into a string starting and ending with single
quote.
Examples of Valid Strings:-

Following examples clarify the rules about creating a string in R.

a <- 'Start and end with single quote'


print(a)

b <- "Start and end with double quotes"


print(b)

c <- "single quote ' in between double quotes"


print(c)

d <- 'Double quotes " in between single quote'


print(d)

Output: -

[1] "Start and end with single quote"


[1] "Start and end with double quotes"
[1] "single quote ' in between double quote"
[1] "Double quote \" in between single quote"

String Manipulation: -

1) Concatenating Strings - paste () function: -

Many strings in R are combined using the paste() function. It can take any number of
arguments to be combined together.

Syntax:-

The basic syntax for paste function is −

paste(..., sep = " ", collapse = NULL)

Following is the description of the parameters used −


Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


 ... represents any number of arguments to be combined.
 sep represents any separator between the arguments. It is optional.
 collapse is used to eliminate the space in between two strings. But not the
space within two words of one string.
Example:-
Live Demo

a <- "Hello"
b <- 'How'
c <- "are you? "

print(paste(a,b,c))

print(paste(a,b,c, sep = "-"))

print(paste(a,b,c, sep = "", collapse = ""))

Output: -

[1] "Hello How are you? "


[1] "Hello-How-are you? "
[1] "HelloHoware you? "

2) Formatting numbers & strings - format () function:-

Numbers and strings can be formatted to a specific style using format () function.

Syntax:_

The basic syntax for format function is −

format(x, digits, nsmall, scientific, width, justify = c("left", "right", "centre", "none"))

Following is the description of the parameters used −

 x is the vector input.


 digits is the total number of digits displayed.
 nsmall is the minimum number of digits to the right of the decimal point.
 scientific is set to TRUE to display scientific notation.
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


 width indicates the minimum width to be displayed by padding blanks in the
beginning.
 justify is the display of the string to left, right or center.

Example:-
Live Demo

# Total number of digits displayed. Last digit rounded off.


result <- format(23.123456789, digits = 9)
print(result)

# Display numbers in scientific notation.


result <- format(c(6, 13.14521), scientific = TRUE)
print(result)

# The minimum number of digits to the right of the decimal point.


result <- format(23.47, nsmall = 5)
print(result)

# Format treats everything as a string.


result <- format(6)
print(result)

# Numbers are padded with blank in the beginning for width.


result <- format(13.7, width = 6)
print(result)

# Left justify strings.


result <- format("Hello", width = 8, justify = "l")
print(result)

# Justfy string with center.


result <- format("Hello", width = 8, justify = "c")
print(result)

Output: -
[1] "23.1234568"
[1] "6.000000e+00" "1.314521e+01"
[1] "23.47000"
[1] "6"
[1] " 13.7"
[1] "Hello "
Mr. P. M. More. (M.C.A.,[Link]., SET,M.B.A., Ph.D(Pursuing)

Assistant Professor

Karmaveer Bhaurao Patil College, Urun Islampur


[1] " Hello "

You might also like