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

R Loops and Control Statements

Control Statements

Uploaded by

Praneesh M
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views36 pages

R Loops and Control Statements

Control Statements

Uploaded by

Praneesh M
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Control Statements & Loops

Prepared by,
Dr M Praneesh
ASST. PROF. In Computer Science With Data Analytics,
Sri Ramakrishna College of Arts & Science,

1
R Looping
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.
2
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 R 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.
Syntax:

for (initialization_Statement; test_Expression; update_Statement)


{
// statements inside the body of the loop
}
3
Flow Diagram:

4
Example 1: Program to display numbers from 1 to 5 using for loop in R

fruits<-list("apple","banana","cherry")

for(x in fruits)
{
print(x)
}

Output

[1] “apple”
[1] “banana”
[1] “cherry” anana"
[1] "cherry«[1]{ 5
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 (expression)
{
statement
}
6
Flow Diagram:

7
Example: Print i as long as i is less than 6

i <- 1
while (i < 6) {
print(i)
i <- i + 1
}

Output
[ 1[[
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5 8
Repeat loop
A repeat loop is used to iterate a block of code. It is a special type of loop in
which there is no condition to exit from the loop. For exiting, we include a break
statement with a user-defined condition. This property of the loop makes it different
from the other loops.
A repeat loop constructs with the help of the repeat keyword in R. It is very easy to
construct an infinite loop in R.
Syntax:

repeat {
commands
if(condition) {
9
break } }
Flow Diagram:

10
Example

v <- c("Hello","repeat","loop")
cnt <- 2
repeat {
print(v)
cnt <- cnt+1
if(cnt > 5)
{
break
}
}

11
Output:

[1] “Hello” “repeat” “loop”


[1] “Hello” “repeat” “loop”
[1] “Hello” “repeat” “loop”
[1] “Hello” “repeat” “loop”

12
Packages in R
R packages are a collection of R functions, complied code and
sample data. They are stored under a directory called "library" in the R
environment. By default, R installs a set of packages during installation.
More packages are added later, when they are needed for some
specific purpose. When we start the R console, only the default
packages are available by default.

Other packages which are already installed have to be loaded explicitly


to be used by the R program that is going to use them.
13
Loading packages in R
For loading a package which is already existing and installed on your system, you
can make use of and call the library function.
Example
>library()
To execute the above code snippet will produce the following result

14
Get all packages currently loaded in the R environment
>search()
To execute the above code will produce the following result

[1] ".GlobalEnv" "package:stats" "package:graphics"


[4] "package:grDevices" "package:utils" "package:datasets"
[7] "package:methods" "Autoloads" "package:base"
Install a New Package
There are two ways to add new R packages. One is installing directly from the
CRAN directory and another is downloading the package to your local system and
installing it manually.
Install directly from CRAN
The following command gets the packages directly from CRAN webpage and installs
the package in the R environment.
[Link]("Package Name") # Install the package named "XML".
[Link]("XML")
15
Install package manually
Go to the link R Packages to download the package
needed. Save the package as a .zip file in a suitable location in the
local system.
Now you can run the following command to install this package in
the R environment.
[Link](file_name_with_path, repos = NULL, type =
"source")
# Install the package named "XML“
[Link]("E:/XML_3.[Link]", repos = NULL, type =
"source")
16
Load Package to Library
Before a package can be used in the code, it must be loaded to
the current R environment. You also need to load a package that is already
installed previously but not available in the current environment.

A package is loaded using the following command −

>library("package Name", [Link] = "path to library")

# Load the package named "XML“


[Link]("E:/XML_3.[Link]", repos = NULL, type = "source")
17
Maintaining packages in R

After your packages get installed and you frequently want to update them in
order to have an up to date latest versions. This is possible using [Link]. By
default, the function will remind you to update each package.
[Link] (ask = FALSE)
# this won't ask for package updating
It may happen that you may want to delete any package. It is possible using
the [Link]().
Example:
[Link]("zoo")
18
Dates and Times in R
Depending on what purposes we're using R for, we may want to deal with
data containing dates and times.
R Provides us various functions to deal with dates and times.
Get Current System Date, and Time in R
In R, we use [Link](), [Link]() to get the current date and time
respectively based on the local system.
For example
# get current system date [Link]()
# get current system time [Link]()
Output
[1] "2022-07-11”
[1] "2022-07-11 04:16:52 UTC"
19
Using R lubridate Package

The lubridate package in R makes the extraction and manipulation of some parts of
the date value more efficient.

There are various functions under this package that can be used to deal with dates.
But first, in order to access the lubridate package, we first need to import the package
as:
# access lubridate package library(lubridate)

[Link] Current Date Using R lubridate Package

# access lubridate package library(lubridate)


# get current date with time and timezone now()
# Output: "2022-07-11 04: 34: 23 UTC" 20
2. Extraction Years, Months, and Days from Multiple Date Values in R
In R, we use the year(), month(), and mday() function provided by
the lubridate package to extract years, months, and days respectively from
multiple date values.
For example,
# import lubridate package library(lubridate)
dates <- c("2022-07-11", "2012-04-19", "2017-03-08")
# extract years from dates year(dates)
# extract months from dates month(dates)
# extract days from dates mday(dates)
21
Output
[1] 2022 2012 2017
[1] 7 4 3
[1] 11 19 8

Here,

year(dates) - returns all years from dates i.e. 2022 2012 2017
month(dates) - returns all months from dates i.e. 7 4 3
mday(dates) - returns days from dates i.e 11 19 8

22
Files in R
In the R programming language, we deal with large amounts of data by
representing data in files. In this regard, we can perform certain operations to
access data like creating files, reading files, renaming them, etc.

Some different file operations in R are:


• Creation of files
• Writing to the files
• Reading data from a file
• Check the existing status of a file
• Renaming the existing files 23
Creation of a file
Using [Link]() function, a new file can be created from console or truncates if
already exists.
Syntax:
[Link](” “)
# Create a file
if ([Link]("[Link]")
print(‘Congrats! Your File Has been created.’)
else
print(‘unable to create’)
Output :[1] "Congrats! Your File Has been created." 24
Writing to the files
[Link]() function in R programming is used to write an object to a file.
Syntax:
[Link](x, file)
Parameters:
x: indicates the object that has to be written into the file
file: indicates the name of the file that has to be written
Example
# into the txt file
[Link](x=toothgrowth[1:10,],”[Link]”)
data=[Link](”[Link]”)
25
Output

len supp dose


1 4.2 VC 0.5
2 11.5 VC 0.5
3 7.3 VC 0.5
4 5.8 VC 0.5
5 6.4 VC 0.5
6 10.0 VC 0.5
7 11.2 VC 0.5
8 11.2 VC 0.5
9 5.2 VC 0.5
10 7.0 VC 0.5

26
Reading data from a file

After the writing data onto a file, we need to read the information from the file using
built-in function. We use the [Link]() function to read the file’s content
that is passed as an argument.
Syntax:
[Link](file)
Parameters:
file: indicates the name of the file that has to be read

Example

# Reading txt file


[Link] <- [Link](file = "[Link]")

# Print 27
Output
X [Link] [Link] [Link] [Link] Species
1 1 5.1 3.5 1.4 0.2 setosa
2 2 4.9 3.0 1.4 0.2 setosa
3 3 4.7 3.2 1.3 0.2 setosa
4 4 4.6 3.1 1.5 0.2 setosa
5 5 5.0 3.6 1.4 0.2 setosa
6 6 5.4 3.9 1.7 0.4 setosa
7 7 4.6 3.4 1.4 0.3 setosa
8 8 5.0 3.4 1.5 0.2 setosa
9 9 4.4 2.9 1.4 0.2 setosa
10 10 4.9 3.1 1.5 0.1 setosa

28
Check an existing file
We can check the file if it exists or not within the current directory or on the
mentioned path using the [Link]() function. We need to pass the file name,
and if the file name is in existence, it returns TRUE. Otherwise, it returns FALSE.
Syntax
[Link](“file_name”)
Example

if ([Link](“[Link]”))
{
print(‘Your file ‘[Link]’ Exist!’)
} 29
Renaming a File

The [Link]() function renames the file and return a logical value.
The function renames files but not directories. It only alters the existing file’s name to a
new name and returns TRUE after successful completion. If the file to rename is not
found, it terminates with the FALSE value.

Syntax:
[Link](from, to)
Parameters:
from: indicates current file name or path
to: indicates new file name or path
Example
# Rename file [Link] to [Link] 30
Making packages in R
Two libraries are required for making a package.

[Link]("devtools")
[Link]("roxygen2")

In RStudio, open File and select New Project and pick the option for R Package. Now
name your project and pick where it will be saved.

Assume that we want to create an R package that includes two functions. The first
function will convert temperatures from degrees Fahrenheit to degrees Celsius, while
the second function will convert temperatures from degrees Celsius to degrees
Fahrenheit. The first thing we need to do is create a new folder somewhere on our
computer that will hold the whole R package 31
The above shows the new folder ‘SCC_R_package’. For now, this folder is
empty. The first thing that we need to do is to create a new folder inside of
‘SCC_R_package’ called ‘R’.
32
Inside this folder is where we will store the actual R scripts with the
coded functions. Any number of ‘.R’ files can be included in the folder, and each
file can have any number of functions. You could, for example, give each
function its own file, or just have one file with many R functions

33
In our new R package, will write both functions in the same file called
‘temp_conversion.R’, which has the code below.
Copy contentsF_to_C <- function(F_temp)
{
C_temp <- (F_temp - 32) * 5/9; return(C_temp);
}
C_to_F <- function(C_temp)
{
F_temp <- (C_temp * 9/5) + 32; return(F_temp);
}
That is the whole file for now; just nine lines of code.

34
The next thing that we need to do is create a new file called DESCRIPTION in
the SCC_R_package directory (note, not in ‘R’, but just outside of it).
This will be a plain text file with no extension, and it will hold some of
the meta-data on the R package. For now, the whole file is just the following four
lines of code, specifying the package name, type, title, and version number.

Package: SCCTempConverter
Type: Package
Title: Temperature Conversion Package for Demonstration
Version: [Link]

If we really wanted to call it quits, this is technically an R package, albeit an extremely


basic one. We could load it using the code above after first reading in
the devtools library.

library(devtools);
Note that the working directory needs to be set correctly to the R package
directory (e.g., using the setwd function, or by choosing Session > Set Working
Directory from the pull down menu of RStudio). In doing this, the above
functions F_to_C and C_to_F are now read into R and we can use them to convert
temperatures.

F_to_C(79);

C_to_F(20);

36

You might also like