Unit 2- R Programming Structure
R is block structured language in the manner of the ALGOL-descendant family, such
as C, C++, Python, Perl, and so on. As you’ve seen, blocks are delineated by braces, though
braces are optional if the block consists of just a single statement. Statements are separated by
newline characters or, optionally, by semicolons.
Control Statements:
Control statements in R look very similar to those to those of the ALGOL-descendant
family languages mentioned above.
Loops:
A loop is a control statement that allows multiple executions of a statement or a set of
statements. The word looping means cycling or iteration.
There are three types of loops in R programming:
• For Loop
• While Loop
• Repeat Loop
For loop in R:
• It is a type of control statement that enables one to easily construct an R loop that has
to run statements or a set of statements multiple times.
• For loop is commonly used to iterate over items of sequence.
• It is an entry-control 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.
• Syntax
for( value in sequence)
{
Statements
}
• Example 1
1
Unit 2- R Programming Structure
• Example 2 : For Loop on list
While Loop in R :
• It is a type of control statement that will run a statement or a set of statements
repeatedly unless the given condition becomes false.
• It is also an entry-controlled loop, in this loop, the test condition is tested first, then
the body of the loop is executed, the loop body would not be executed if the test
condition is false.
• Syntax
while(condition)
{
Statements
}
• Example
Repeat Loop in R:
• It is a simple loop that will run the same statement or a group of statements repeatedly
until the stop condition has been encountered.
• Repeat loop does not have any condition to terminate the loop, a programmer must
specifically place a condition within the loop’s body and use the declaration of a break
statement to terminate this loop.
• If no condition is present in the body of the repeat loop then it will iterate infinitely.
2
Unit 2- R Programming Structure
• Syntax
repeat
{
statement
if(condition)
{
break
}
}
Looping Over NonVector Sets :
R does not directly support iteration over non vector sets, but there are a couple of
indirect yet easy ways to accomplish it.
• apply() :
o This function applies a given function over the margins of a given array.
o Syntax
o Example
3
Unit 2- R Programming Structure
• lapply():
o This function is used to apply a function over a list. It always returns a list of
the same length as the input list.
o Syntax
o Example
• sapply():
o This function is used to simplify the result of lapply(), if possible.
Unlike lapply(), the result is not always a list. The output varies in the
following ways:-
▪ If output is a list containing elements having length 1, then a vector is
returned.
▪ If output is a list where all the elements are vectors of same length(>1),
then a matrix is returned.
▪ If output contains elements which cannot be simplified or elements of
different types, a list is returned.
o Syntax
4
Unit 2- R Programming Structure
o Example
• tapply():
o This function is used to apply a function over subset of vectors given by a
combination of factors.
o Syntax
o Example
if-else
• The if-statement in Programming Language alone tells us that if a condition is true it
will execute a block of statements and if the condition is false it won’t.
• But what if we want to do something else if the condition is false? Here comes the R
Programming Language else statement.
• We can use the else statement with the if statement to execute a block of code when
the condition is false.
• Syntax:
ifesle(testcondition, yes, no)
5
Unit 2- R Programming Structure
• Example
Arithmetic and Boolean Operators and Values
Operations Description
x+y Addition
x-y Substraction
x*y Multiplication
x/y Division
x^y Exponentiation
x %% y Modular Arithmetic
x %/% y Integer Division
x == y Test for Equality
x <= y Test for less than or equal to
x >= y Test for greater than equal to
x && y Boolean AND for Scalars
x || y Boolean OR for Scalars
x&y Boolean And for vectors
x|y Boolean OR for vectors
!x Boolean Negation
Default Value for argument
• Arguments are the parameters provided to a function to perform operations in a
programming language.
• In R programming, we can use as many arguments as we want and are separated by a
comma.
• There is no limit on the number of arguments in a function in R. In this article, we’ll
discuss different ways of adding arguments in a function in R programming.
o Return Values:
▪ 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.
▪ Syntax
function_name(parametres)
{
Statements
return(value)
}
funntion_name(values)
6
Unit 2- R Programming Structure
o Deciding Whether to explicitly call return
▪ Here without using return function we will return a value. For this just
passing the name of the variable that stores the value to returned
works.
7
Unit 2- R Programming Structure
o Returning Complex Object
▪ In this scenario, we will use the list() function in the return statement to
return multiple values.
▪ Syntax
8
Unit 2- R Programming Structure
Functions are objectives
• R functions are first-class objects (of the class "function"), meaning that they can be
used for the most part just like other objects.
• This is seen in the syntax of function creation:
• function( ) is a built-in R function whose job is to create functions.
• On the right-hand side, there are really two arguments to function(): The first is the
formal argument list for the function i.e, x and the second is the body of that function
return(x+1).
• That second argument must be of class "expression". So, the point is that the right-
hand side creates a function object, which is then assigned to g.
o formals( ) :- Get or set the formal arguments of a function
o body( ) :- Get or set the body of a function
o Replacing body of the function: quote( ) is used to substitute expression
o Printing out a function is also useful if you are not quite sure what an R library
function does.
o Code of a function is displayed by typing the built-in function name.
9
Unit 2- R Programming Structure
o Some of R‘s most fundamental built-in functions are written directly in C, and
thus they are not viewable in this manner
No pointers in R
• R does not have variables corresponding to pointers or references like C language.
This can make programming more difficult in some cases.
• The fundamental thought is to create a class constructor and have every instantiation
of the class be its own environment.
• One can then pass the object/condition into a function and it will be passed by
reference instead of by value, because unlike other R objects, environments are not
copied when passed to functions.
• Changes to the object in the function will change the object in the calling frame. In
this way, one can operate on the object and change internal elements without having
to create a copy of the object when the function is called, nor pass the entire object
back from the function. For large objects, this saves memory and time.
• For example, you cannot write a function that directly changes its arguments.
• The argument to sort() does not change. If we do want x to change in this R code, the
solution is to reassign the arguments:
• If a function has several output then a solution is to gather them together into a list,
call the function with this list as an argument, have the function return the list, and
then reassign to the original list.
• An example is the following function, which determines the indices of odd and even
numbers in a vector of integers:
10
Unit 2- R Programming Structure
Recursion
• Recursion is a programming technique in which, a function calls itself repeatedly for
some input
• To solve a problem of type X by writing a recursive function f():
1. Break the original problem of type X into one or more smaller problems of
type X. 2. Within f(), call f() on each of the smaller problems.
3. Within f(), piece together the results of (b) to solve the original problem.
Quick Sort Implementation
• Quick sort is also known as Partition-Exchange sort and is based on Divide and
conquer Algorithm design method.
• This was proposed by C.A.R Hoare. The basic idea of quick sort is very simple. We
consider one element at a time (pivot element).
• We have to move the pivot element to the final position that it should occupy in the
final sorted list.
• While identifying this position, we arrange the elements, such that the elements to the
left of the pivot element will be less than pivot element & elements to the right of the
pivot element will be greater than pivot element.
• There by dividing the list by 2 parts. We have to apply quick sort on these 2 parts
recursively until the entire list is sorted.
• For instance, suppose we wish to sort the vector (5,4,12,13,3,8,88). We first compare
everything to the first element, 5, to form two subvectors: one consisting of the
elements less than 5 and the other consisting of the elements greater than or equal to
5.
• That gives us subvectors (4,3) and (12,13,8,88). We then call the function on the
subvectors, returning (3,4) and (8,12,13,88).
• We string those together with the 5, yielding (3,4,5,8,12,13,88), as desired. R‘s
vector-filtering capability and its c() function make implementation of Quicksort quite
easy.
11
Unit 2- R Programming Structure
A Binary Search Tree
• The nature of binary search trees implies that at any node, all of the elements in the
node‘s left subtree are less than or equal to the value stored in this node, while the
right subtree stores the elements that are larger than the value in this mode.
• In our example tree, where the root node contains 8, all of the values in the left
subtree-5, 2 and 6-are less than 8, while 20 is greater than 8
Error handling
• Error Handling is a process in which we deal with unwanted or anomalous errors
which may cause abnormal termination of the program during its execution.
• In R Programming, there are basically two ways in which we can implement an error
handling mechanism.
• Either we can directly call the functions like stop() or warning(), or we can use the
error options such as “warn” or “[Link]”.
• The basic functions that one can use for error handling in the code :
o stop(…): It halts the evaluation of the current statement and generates a
message argument. The control is returned to the top level.
o waiting(…): Its evaluation depends on the value of the error option warn. If
the value of the warning is negative then it is ignored. In case the value is 0
(zero) they are stored and printed only after the top-level function completes
its execution. If the value is 1 (one) then it is printed as soon as it has been
encountered while if the value is 2 (two) then immediately the generated
warning is converted into an error.
o tryCatch(…): It helps to evaluate the code and assign the exceptions.
Conditional Handling in R
• Generally, if we encounter any unexpected errors while executing a program we need
an efficient and interactive way to debug the error and know what went wrong.
• However, some errors are expected but sometimes the models fail to fit and throw an
error. There are basically three methods to handle such conditions and errors in R :
o try(): it helps us to continue with the execution of the program even when an
error occurs.
o tryCatch(): it helps to handle the conditions and control what happens based
on the conditions.
o withCallingHandlers(): it is an alternative to tryCatch() that takes care of the
local handlers.
12
Unit 2- R Programming Structure
try-catch-finally in R
• Unlike other programming languages such as Java, C++, and so on, the try-catch-
finally statements are used as a function in R.
• The main two conditions to be handled in tryCatch() are “errors” and “warnings”.
• Syntax
13
Unit 2- R Programming Structure
withCallingHandler() in R
• In R, withCallingHandlers() is a variant of tryCatch().
• The only difference is tryCatch() deals with exiting handlers while
withCallingHandlers() deals with local handlers.
14
Unit 2- R Programming Structure
15