R Loops and Control Statements
R Loops and Control Statements
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
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
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:
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.
14
Get all packages currently loaded in the R environment
>search()
To execute the above code will produce the following result
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)
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.
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
# 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]
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