0% found this document useful (0 votes)
1 views36 pages

Unit-2 2BCA R Programming

The document provides an overview of control statements and loops in R programming, detailing various types such as if conditions, for loops, while loops, and switch statements. It also discusses built-in and user-defined functions, exception handling methods, and timing functions for measuring code execution. Key concepts include the use of break and next statements, as well as the importance of error handling for robust and maintainable code.

Uploaded by

nneha2979
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)
1 views36 pages

Unit-2 2BCA R Programming

The document provides an overview of control statements and loops in R programming, detailing various types such as if conditions, for loops, while loops, and switch statements. It also discusses built-in and user-defined functions, exception handling methods, and timing functions for measuring code execution. Key concepts include the use of break and next statements, as well as the importance of error handling for robust and maintainable code.

Uploaded by

nneha2979
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

BENGALURU NORTH UNIVERSITY

Bachelor of Computer Applications (BCA)


Semester: 2nd Sem BCA
CA2T2: Statistical
Methods using
R Programming

[Link]
UNIT-II

[Link] 2
Conditions and Loops:
Control statements are expressions used to control the execution and flow of
the program based on the conditions provided in the statements. These
structures are used to make a decision after assessing the variable.
In R programming, there are 8 types of control statements as follows:
➢ if condition
➢ if-else condition
➢ for loop
➢ nested loops
➢ while loop
➢ repeat and break statement
➢ return statement
➢ next statement

[Link] 3
if condition Statement
This control structure checks the expression provided in parenthesis is true
or not. If true, the execution of the statements in braces {} continues.

Here, the Condition is a Boolean expression. It returns either True or False.


If the Condition is
True - body of the if statement is executed
False - body of the if statement is skipped
Example:

[Link] 4
if...else Statement

In this statement, if the condition is true statement1 is executed, but when


the condition fails, then statement2 in else condition are executed,

[Link] 5
if-else-if Ladder
This structure chains multiple conditions together. Each condition is
evaluated in sequence. If a condition is TRUE, its block is executed.
Otherwise, the next condition is checked.

[Link] 6
switch() Statement
The switch() function provides a convenient way to select one of several
alternatives based on a given value or condition. It is often used as an
alternative to multiple if statements or nested if-else statements when there
are a limited set of options to choose from.

In this pseudo-code:
expr is the expression or value that needs to be evaluated.
case1, case2, case3, and so on, are the possible cases or alternatives to be
considered.
The expr value is compared with each case value sequentially, and when a
match is found, the corresponding expression or value associated with that
case is returned.

[Link] 7
In this example, the day variable is set to 3. The switch() function then
compares the value of day with each case value. Since the third case
matches, the corresponding value "Wednesday" is returned and assigned to
the variable weekday.

Simple Calculator Example


From the below example, one can easily compute some basic computations
on two numbers. The operation on these two numbers depends on the input
given to readline( ) the function and the expression in the switch. The
operator value from readline() is matched with the options (cases) in the
switch statement and results are displayed when matched.

[Link] 8
Output:

for Loop

A for loop is used to iterate over a list, vector or any other object of
elements.

Syntax:

[Link] 9
Write a R Program to Display even numbers up to N terms.

While Loop
The While loop executes the same code again and again until a condition is
met. A while loop is used when you want to perform a task indefinitely, until
a particular condition is met. It’s a condition-controlled loop.
Syntax:

[Link] 10
Example: Output:

Repeat Loop
A repeat loop just repeats a block of code indefinitely. In this loop, no
condition checking is performed in order to end the loop.
To stop repeating the loop, you must put a condition explicitly inside it with
break statement. Failing to do so will create an infinite loop.
Syntax:

[Link] 11
Example:

[Link] 12
Program to reverse a given number

Program to find sum of first n natural number

[Link] 13
Break, Next, and goto statement in R Programming
Break Statement in R:
The break Statement in R is a jump statement that is used to terminate the
loop at a particular iteration. A break statement is used inside a loop
(repeat, for, while) to stop the iterations and flow the control outside of the
loop.
Example: Output:

Next Statement in R:
The next statement in R is used to skip the current iteration in the loop and
move to the next iteration without exiting from the loop itself.
Example: Output:

goto statement in R:
The goto statement is not natively supported in the R programming
language. Using goto can make code difficult to follow, debug, and maintain
over time, as it can create complex, tangled execution paths. The structured
programming theorem proved that goto is not necessary to write any
program, as combinations of sequence, selection, and iteration constructs
are sufficient.

[Link] 14
R-Function
A function is a block of code that you can call and run from any part of your
program. They are used to break our code in simple parts and avoid
repeatable codes.
R has many in-built functions which can be directly called in the program
without defining them first. We can also create and use our own functions
referred as user defined functions.

Built-in Functions in R
R contains a wide variety of built-in functions in the base R package. Build-in
functions are pre-defined functions available to the user in R. These
functions enable the user to perform some common operations without any
need to implement them.
Some of the basic math built-in functions are,
min(), max(), mean(), median() – return the minimum / maximum / mean
/ median value of a numeric vector, correspondingly
sum() – returns the sum of a numeric vector
abs() – returns the absolute value of a number
ceiling() - Rounds a number up to the nearest integer (smallest integer not less
than x).
floor() - Rounds a number down to the nearest integer (largest integer not greater
than x).

[Link] 15
trunc() - Truncates the number towards zero, returning the integer part and
removing the fractional part.
round() - Rounds to the specified number of digits (default is 0, for the nearest
integer). R uses an "round to even" rule when the fractional part is exactly 0.5
(e.g., round(2.5) is 2, round(3.5) is 4).
cos() - Calculates the cosine of the angle x (in radians).
sin() - Calculates the sine of the angle x (in radians).
tan() - Calculates the tangent of the angle x (in radians).
Example:

[Link] 16
Output:

String Function in R:
R provides many built-in functions to facilitate string manipulation. some of
the most commonly used functions are:
nchar() - Returns the number of characters in a string.
substr() - Extracts substrings from a string.
toupper() - Converts strings to uppercase.
tolower() - Converts strings to lowercase.
trimws() - Removes leading and trailing whitespace.
paste() - paste() is used to join two or more strings together. This is known
as concatenation.
strsplit() - Splits the elements of a character vector into substrings based
on a specified delimiter or pattern, returning a list of character vectors.
sprintf() – A powerful function that provides C-style string formatting.
It allows for precise control over the output format of various data types.
grep() – grep is a utility for searching text for lines that match a regular
expression. The name stands for: globally search for a regular expression
and print matching lines.

[Link] 17
Example:

[Link] 18
User Defined Function:
User-defined functions (UDFs) in R are reusable blocks of code created by
the user to perform specific, often repetitive, tasks. They enhance code
modularity, readability, and efficiency.
In R programming, user-defined functions are functions created by the user,
as opposed to the built-in functions included in R. If you need a certain
functionality that can be reused but is not readily available in R, then you
can create it on your own.
You can pass data into functions with the help of parameters and return
some other data as a result. You can use the function() reserve keyword to
create a function in R.
The basic syntax of an R function definition is as follows,

Function Components
The different parts of a function are −
Function Name: This is the actual name of the function. It is stored in R
environment as an object with this name.
Arguments: An argument is a placeholder. When a function is invoked, you
pass a value to the argument. Arguments are optional; that is, a function
may contain no arguments. Also, arguments can have default values.
Function Body: The function body contains a collection of statements that
defines what the function does.
Return Value: The return value of a function is the last expression in the
function body to be evaluated.

[Link] 19
How to call R function?
To call a function, we simply have to use the function’s name and provide
appropriate arguments.

Where function_name is the name of the function you want to call,


and arguments are the arguments needed by the function, arguments are
optional.

Example on Function

[Link] 20
R Program to Calculate Simple Interest using the Function.

R Program to Check whether given number is even or odd numbers.

[Link] 21
Scope of R functions
An environment is the collection of all the variables and objects. The top-
level of the environment is the global environment. When we create a
function, it creates a local environment that exists in the global
environment. The function operates inside the local environment.
Local vs global variables
Global variables are variables declared in a global scope that is they are
accessible from anywhere in the global environment.
Local variables are variables declared in a local scope i.e. they are only
accessible inside their local environment.
Note: Global variables are accessible inside local environments but local
variables are not accessible outside their local environments.
Variables and objects created inside a function, exist only inside the
function’s local environment. If an object does not exist inside the function’s
local environment, then the interpreter tries to find it in the global
environment.

Recursive functions
if a function that calls itself is called recursive function. It is used to solve a
problem by breaking it down into smaller, simpler sub-problems.
Write a R program to find its factorial using recursive.

[Link] 22
Exception Handling.
Exception handling in R is the process of managing unexpected errors,
warnings, or messages that occur during program execution to prevent the
code from crashing abruptly. It allows developers to provide alternative
actions, custom messages, and ensure the program continues to run
gracefully.
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 :
• try(): it helps us to continue with the execution of the program even
when an error occurs.
• tryCatch(): it helps to handle the conditions and control what happens
based on the conditions.
• withCallingHandlers(): it is an alternative to tryCatch() that takes
care of the local handlers.

Using try
We need to enclose the objectionable statements in the try block. The
statements passed inside are like arguments to a function. In case you
have more than one statements, it is preferred that you write a function with
all those statements and call the function inside the try block.

Example:

[Link] 23
Output:

Using the try block we can see the code ran for all the other cases even after
the error in one of the iterations.

Using tryCatch
the tryCatch() function in R is a powerful tool that helps you handle errors
and warnings that might occur during code execution. By using tryCatch(),
you can ensure your program continues running even when unexpected
issues arise.

Let’s break down each component:

1. expr: The R code you want to run and monitor for errors or
warnings.
2. error: A function that runs if an error occurs in your expression.
3. warning: A function that runs if a warning occurs in your
expression.
4. finally: Code that executes regardless of whether errors or
warnings occurred.

[Link] 24
Output:

In this example, attempting to take the square root of a non-numeric value


generates an error. The tryCatch() function catches this error and prints a
custom message, returning NA as the result.

CallingHandlers() in R
the CallingHandlers() function is a powerful and advanced tool that allows
you to define and customize error handlers for different types of errors. It's
like having a specialized team ready to tackle specific issues that may arise
in your code.

[Link] 25
Here's what each component does:
• The code to be tested goes inside the curly braces following
withCallingHandlers().
• The error parameter specifies a custom error-handling function,
similar to tryCatch().

Example

CallingHandlers() in R
The CallingHandlers() function is a powerful and advanced tool that allows
you to define and customize error handlers for different types of errors. It's
like having a specialized team ready to tackle specific issues that may arise
in your code.

Here's what each component does:


• The code to be tested goes inside the curly braces following
withCallingHandlers().
• The error parameter specifies a custom error-handling function,
similar to tryCatch().

[Link] 26
Advantages of Using Error Handling in R
Error handling in R offers several advantages that contribute to the overall
robustness and reliability of your code. Let's explore these advantages in
detail:
Robustness:
Error handling makes your R code more robust by allowing it to gracefully
handle unexpected situations without crashing.
Improved Debugging:
It simplifies debugging by providing informative error messages, aiding in
quicker issue identification and resolution.
User-Friendly:
Error messages enhance the user experience by providing clear feedback
when errors occur, reducing user frustration.
Maintainability:
Isolating error-handling logic from the main code improves code
maintainability, making it easier to manage and modify.
Continued Execution:
Error handling ensures your program can continue running even when errors
occur, preventing total disruptions in critical processes.

[Link] 27
Timing Function
In R programming, the primary functions for measuring code execution time
are built-in functions like [Link](), [Link](), and [Link](), as well
as specialized packages like tictoc and microbenchmark.
1. Method 1: Use [Link]()
An easy way to measure the execution time of a piece of code is by using
the built-in [Link]() function.
To measure the execution time with the [Link]() function:
Call [Link]() before the part of code you want to measure and store the
time instance into a variable.
Run the piece of code whose execution time you want to measure.
Call [Link]() again and store the time instance to a variable.
Subtract the last [Link]() call from the first [Link]() call. This returns a
description of the time difference between these two instances of time.
Example:

Output

[Link] 28
Method 2: Use [Link]()
Another way to measure the execution time in R is by using the
[Link]() function. Unlike the [Link]() function, the [Link]()
function takes an expression, evaluates it, and measures the elapsed time.
Here’s an example of measuring how long it takes to run an example
function:

Output:

Here’s a more specific breakdown of the returned values:


1. user. This is the user CPU time spent by the current R session.
2. system. This is the system CPU time that the operating system spent on
behalf of the current process.
3. elapsed. The execution time of the actual code you are measuring.

[Link] 29
Method 3: Use microbenchmark Library
Another library you might want to consider to measure the execution time of
your program is the microbenchmark library.
To then use this library to measure the elapsed time, you need to run code
inside the microbenchmark() function call.
This function not only returns the time it took to execute your code but also
some useful details, such as minimum time, maximum time, median elapsed
time, and such based on the numerous runs the function performs.
Example:

Output:

Let’s take a quick look at the returned values:


1. expr is the code expression you want to find the execution time for.
2. min is the minimum amount of time it took to run the code out of the
numerous tries.
3. lq is the lower quartile, that is, 25% of the runs took at most this
amount of time to run.
4. mean is the average execution time.
5. median is the median time it took to run the code.
6. uq is the upper quartile, that is, 75% of the runs took at most this
amount of time to run.
7. max is the maximum amount of time that the code ran.
8. neval is the number of evaluations which is 100 by default.

[Link] 30
Method 4: Use rbenchmark Library
rbenchmark is another useful timing library for measuring execution times.
rbenchmark is a great alternative to the [Link]() function is the
rbenchmark library.
Once again, you need to install this library before using it!
Very similar to the previous examples, the rbenchmark library comes with a
built-in timing function, benchmark(). This function takes the piece of code
you want to time as an argument. It then returns a bunch of data related to
the runs it performed.
Notice that this method returns the total amount of time elapsed. By default,
the function runs your code 100 times. So for example, if your code takes 1
second to run, this method returns an elapsed time of 100 seconds because
it runs the code 100 times.
For example, let’s measure the execution time of an example function.

Output:

[Link] 31
Visibility
The location where we can find a variable and also access it if required is
called the scope of a variable. There are mainly two types of variable
scopes:
Global Variables: As the name suggests, Global Variables can be accessed
from any part of the program.
They are available throughout the lifetime of a program.
They are declared anywhere in the program outside all of the functions or
blocks.
Declaring global variables: Global variables are usually declared outside
of all of the functions and blocks. They can be accessed from any portion
of the program.
Example:

Output:

[Link] 32
Local Variable:
Local Variables: Variables defined within a function or block are said to be
local to those functions.
These Local variables do not exist outside the block in which they are
declared, i.e. they cannot be accessed or used outside that block.
Declaring local variables: Local variables are declared inside a block.
Example:

Output:

[Link] 33
Packages in R Programming
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.

Repositories of R programming packages


A repository is a place where packages are located and stored so we can
install R 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 specialized 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.

[Link] 34
Installing Packages Using RStudio UI
In R Studio goto Tools -> Install Package, and there we will get a pop-up
window to type the package we want to install:

Under Packages, type, and search Package which we want to install and then
click on install button.
How to Load Packages in R Programming Language
When a R package is installed, we are ready to use its functionalities. If we
just need a sporadic use of a few functions or data inside a package we can
access them with the following notation.
Example:
Load a package using the library function
library(dplyr)
Alternatively, load a package using the require function
require(dplyr)
Both functions attempt to load the specified package, but there is a subtle
difference between the two: library() returns an error if the package is not
found or cannot be loaded, whereas require() returns a warning and sets the
value of the package variable to FALSE.

[Link] 35
Difference Between a Package and a Library
There is always confusion between a package and a library, and we find
people calling libraries as packages.
library(): It is the command used to load a package, and it refers to the
place where the package is contained, usually a folder on our computer.
Package: It is a collection of functions bundled conveniently. The package is
an appropriate way to organize our own work and share it with others.

****

[Link] 36

You might also like