0% found this document useful (0 votes)
11 views

R Programming UNIT 2

The document provides an overview of reading and writing files in R programming, focusing on CSV, text, and XML file formats. It details functions such as read.csv(), write.csv(), and xmlParse() for importing and exporting data, along with examples and syntax for each function. Additionally, it covers how to perform operations on CSV and XML data, including querying and extracting information.

Uploaded by

Chaya Anu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

R Programming UNIT 2

The document provides an overview of reading and writing files in R programming, focusing on CSV, text, and XML file formats. It details functions such as read.csv(), write.csv(), and xmlParse() for importing and exporting data, along with examples and syntax for each function. Additionally, it covers how to perform operations on CSV and XML data, including querying and extracting information.

Uploaded by

Chaya Anu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 119

Reading Files in R Programming

So far the operations using the R program are done on a prompt/terminal


which is not stored anywhere. But in the software industry, most of the
programs are written to store the information fetched from the program. One
such way is to store the fetched information in a file. So the two most
common operations that can be performed on a file are:
 Importing/Reading Files in R
 Exporting/Writing Files in R

read.csv(): read.csv() is used for reading “comma separated value” files


(“.csv”). In this also the data will be imported as a data frame.
Syntax: read.csv(file, header = TRUE, sep = “,”, dec = “.”, …)
Parameters:
 file: the path to the file containing the data to be imported into R.
 header: logical value. If TRUE, read.csv() assumes that your file has a
header row, so row 1 is the name of each column. If that’s not the case,
you can add the argument header = FALSE.
 sep: the field separator character
 dec: the character used in the file for decimal points.

Example:
 R

# R program to read a file in table format

# Using read.csv()

myData = read.csv("basic.csv")

print(myData)

Output:
Name Age Qualification Address
1 Amiya 18 MCA BBS
2 Niru 23 Msc BLS
3 Debi 23 BCA SBP
4 Biku 56 ISC JJP
read.csv2(): read.csv() is used for variant used in countries that use a
comma “,” as decimal point and a semicolon “;” as field separators.
Syntax: read.csv2(file, header = TRUE, sep = “;”, dec = “,”, …)
Parameters:
 file: the path to the file containing the data to be imported into R.
 header: logical value. If TRUE, read.csv2() assumes that your file has a
header row, so row 1 is the name of each column. If that’s not the case,
you can add the argument header = FALSE.
 sep: the field separator character
 dec: the character used in the file for decimal points.

Example:
 R

# R program to read a file in table format

# Using read.csv2()

myData = read.csv2("basic.csv")

print(myData)

Output:
Name.Age.Qualification.Address
1 Amiya,18,MCA,BBS
2 Niru,23,Msc,BLS
3 Debi,23,BCA,SBP
4 Biku,56,ISC,JJP
file.choose(): You can also use file.choose() with read.csv() just like
before.
Example:
 R

# R program to read a file in table format

# Using file.choose() inside read.csv()


myData = read.csv(file.choose())

# If you use the code above in RStudio

# you will be asked to choose a file

print(myData)

Output:
Name Age Qualification Address
1 Amiya 18 MCA BBS
2 Niru 23 Msc BLS
3 Debi 23 BCA SBP
4 Biku 56 ISC JJP
read_csv(): This method is also used for to read a comma (“,”) separated
values by using the help of readr package.
Syntax: read_csv(file, col_names = TRUE)
Parameters:
 file: the path to the file containing the data to be read into R.
 col_names: Either TRUE, FALSE, or a character vector specifying column
names. If TRUE, the first row of the input will be used as the column
names.
Example:
 R

# R program to read a file in table format

# using readr package

# Import the readr library

library(readr)

# Using read_csv() method


myData = read_csv("basic.csv", col_names = TRUE)

print(myData)

Output:
Parsed with column specification:
cols(
Name = col_character(),
Age = col_double(),
Qualification = col_character(),
Address = col_character()
)
# A tibble: 4 x 4
Name Age Qualification Address

1 Amiya 18 MCA BBS


2 Niru 23 Msc BLS
3 Debi 23 BCA SBP
4 Biku 56 ISC JJP
Reading a file from the internet
It’s possible to use the
functions read.delim(), read.csv() and read.table() to import files from the
web.
Example:
 R

# R program to read a file from the internet

# Using read.delim()

myData = read.delim("http://www.sthda.com/upload/boxplot_format.txt")

print(head(myData))

Output:

Nom variable Group


1 IND1 10 A
2 IND2 7 A
3 IND3 20 A
4 IND4 14 A
5 IND5 14 A
6 IND6 12 A

Writing to Files in R Programming


R programming Language is one of the very powerful languages specially
used for data analytics in various fields. Analysis of data means reading and
writing data from various files like excel, CSV, text files, etc. Today we will be
dealing with various ways of writing data to different types of files using R
programming.
R – Writing to Files

Writing Data to CSV files in R Programming Language

CSV stands for Comma Separated Values. These files are used to handle a
large amount of statistical data. Following is the syntax to write to a CSV file:
Syntax:
 R

write.csv(my_data, file = "my_data.csv")

write.csv2(my_data, file = "my_data.csv")

Here,
csv() and csv2() are the function in R programming.
 write.csv() uses “.” for the decimal point and a comma (“, ”) for the
separator.
 write.csv2() uses a comma (“, ”) for the decimal point and a semicolon
(“;”) for the separator.
Writing Data to text files

Text files are commonly used in almost every application in our day-to-day
life as a step for the “Paperless World”. Well, writing to .txt files is very similar
to that of the CSV files. Following is the syntax to write to a text file:

Syntax:
 R

write.table(my_data, file = "my_data.txt", sep = "")

Writing Data to Excel files

To write data to excel we need to install the package known as “xlsx


package”, it is basically a java based solution for reading, writing, and
committing changes to excel files. It can be installed as follows:
install.packages("xlsx")
and can be loaded and General syntax of using it is:

 R

library("xlsx")
write.xlsx(my_data, file = "result.xlsx",

sheetName = "my_data", append = FALSE).

Working with CSV files in R Programming


 Read

 Discuss

 Courses

 Practice



CSV files are basically the text files wherein the values of each row
are separated by a delimiter, as in a comma or a tab. In this article,
we will use the following sample CSV file:
sample.csv
id, name, department, salary, projects
1, A, IT, 60754, 4
2, B, Tech, 59640, 2
3, C, Marketing, 69040, 8
4, D, Marketing, 65043, 5
5, E, Tech, 59943, 2
6, F, IT, 65000, 5
7, G, HR, 69000, 7
Reading a CSV file
The contents of a CSV file can be read as a data frame in R using the
read.csv(…) function. The CSV file to be read should be either
present in the current working directory or the directory should be
set accordingly using the setwd(…) command in R. The CSV file can
also be read from a URL using read.csv() function.
Examples:

csv_data <- read.csv(file = 'sample.csv')

print(csv_data)

# print number of columns

print (ncol(csv_data))

# print number of rows

print(nrow(csv_data))

Output:
id, name, department, salary, projects
1 1 A HR 60754 14
2 2 B Tech 59640 3
3 3 C Marketing 69040 8
4 4 D HR 65043 5
5 5 E Tech 59943 2
6 6 F IT 65000 5
7 7 G HR 69000 7
[1] 4
[1] 7
The header is by default set to a TRUE value in the function. The
head is not included in the count of rows, therefore this CSV has 7
rows and 4 columns.
Querying with CSV files
SQL queries can be performed on the CSV content, and the
corresponding result can be retrieved using the subset(csv_data,)
function in R. Multiple queries can be applied in the function at a
time where each query is separated using a logical operator. The
result is stored as a data frame in R.
Examples:

csv_data <- read.csv(file ='sample.csv')

min_pro <- min(csv_data$projects)

print (min_pro)

Output:
2
Aggregator functions (min, max, count etc.) can be applied on the
CSV data. Here the min() function is applied on projects column
using $ symbol. The minimum number of projects which is 2 is
returned.

csv_data <- read.csv(file ='sample.csv')

new_csv <- subset(csv_data, department == "HR" & projects <10)

print (new_csv)

Output:

id, name, department, salary, projects


4 4 D HR 65043 5
7 7 G HR 69000 7
The subset of the data that is created is stored as a data frame
satisfying the conditions specified as the arguments of the function.
The employees D and G are HR and have the number of
projects<10. The row numbers are retained in the resultant data
frame.
Writing into a CSV file
The contents of the data frame can be written into a CSV file. The
CSV file is stored in the current working directory with the name
specified in the function write.csv(data frame, output CSV name) in
R.
Examples:

csv_data <- read.csv(file ='sample.csv')

new_csv <- subset(csv_data, department == "HR" & projects <10)

write.csv(new_csv, "new_sample.csv")

new_data <-read.csv(file ='new_sample.csv')

print(new_data)

Output:

X id, name, department, salary, projects


1 4 4 D HR 65043 5
2 7 7 G HR 69000 7
The column X contains the row numbers of the original CSV file. In
order to remove it, we can specify an additional argument in the
write.csv() function that set row names to FALSE.

csv_data <- read.csv(file ='sample.csv')

new_csv <- subset(csv_data, department == "HR" & projects <10)

write.csv(new_csv, "new_sample.csv", row.names = FALSE)


new_data <-read.csv(file ='new_sample.csv')

print(new_data)

Output:

id, name, department, salary, projects


1 4 D HR 65043 5
2 7 G HR 69000 7
The original row numbers are removed from the new CSV.

Working with XML Files in R Programming


XML which stands for Extensible Markup Language is made up of markup
tags, wherein each tag illustrates the information carried by the particular
attribute in the XML file. We can work with the XML files using the XML
package provided by R. The package has to be explicitly installed using the
following command:
install.packages("XML")
Creating XML file
XML files can be created by saving the data with the respective tags
containing information about the content and saving it with ‘.xml’.
We will use the following XML file ‘sample.xml’ to see the various operations
that can be performed on the file:

 HTML

<RECORDS>

<STUDENT>

<ID>1</ID>

<NAME>Alia</NAME>

<MARKS>620</MARKS>
<BRANCH>IT</BRANCH>

</STUDENT>

<STUDENT>

<ID>2</ID>

<NAME>Brijesh</NAME>

<MARKS>440</MARKS>

<BRANCH>Commerce</BRANCH>

</STUDENT>

<STUDENT>

<ID>3</ID>

<NAME>Yash</NAME>

<MARKS>600</MARKS>

<BRANCH>Humanities</BRANCH>

</STUDENT>

<STUDENT>

<ID>4</ID>

<NAME>Mallika</NAME>

<MARKS>660</MARKS>

<BRANCH>IT</BRANCH>

</STUDENT>
<STUDENT>

<ID>5</ID>

<NAME>Zayn</NAME>

<MARKS>560</MARKS>

<BRANCH>IT</BRANCH>

</STUDENT>

</RECORDS>

Reading XML File


The XML file can be read after installing the package and then parsing it
with xmlparse() function, which takes as input the XML file name and prints
the content of the file in the form of a list. The file should be located in the
current working directory. An additional package named ‘methods’ should
also be installed. The following code can be used to read the contents of the
file “sample.xml”.
 Python3

# loading the library and other important packages

library("XML")

library("methods")

# the contents of sample.xml are parsed

data <- xmlParse(file = "sample.xml")

print(data)
Output:
1
Alia
620
IT
2
Brijesh
440
Commerce
3
Yash
600
Humanities
4
Mallika
660
IT
5
Zayn
560
IT
Extracting information about the XML file
XML files can be parsed and operations can be performed on its various
components. There are various in-built functions available in R, to extract the
information of the nodes associated with the file, getting the number of nodes
in the file, and also the specific attributes of some particular node in the file.

 Python3

# loading the library and other important packages

library("XML")

library("methods")
# the contents of sample.xml are parsed

# Load the packages required to read XML files.

library("XML")

library("methods")

# Give the input file name to the function.

res <- xmlParse(file = "sample.xml")

# Extract the root node.

rootnode <- xmlRoot(res)

# number of nodes in the root.

nodes <- xmlSize(rootnode)

# get entire contents of a record

second_node <- rootnode[2]

# get 3rd attribute of 4th record

attri <- rootnode[[4]][[3]]


cat('number of nodes: ', nodes)

print ('details of 2 record: ')

print (second_node)

# prints the marks of the fourth record

print ('3rd attribute of 4th record: ', attr)

Output:
[1] number of nodes: 5
[2] details of 2 record:
$STUDENT
2
Brijesh
440
Commerce
[3] 3rd attribute of 4th record: 660
Conversion of XML to dataframe
In order to enhance the readability of the data, the XML data can be
converted into a data frame consisting of a data frame comprising of rows
and columns. R contains an in-built function xmlToDataFrame() which
contains as input the XML file and outputs the corresponding data in the form
of a data frame. This simulates the easy handling and processing of large
amounts of data.

 Python3

# Load the required packages.

library("XML")
library("methods")

# Convert the input xml file to a data frame.

dataframe <- xmlToDataFrame("sample.xml")

print(dataframe)

Output:
ID NAME MARKS BRANCH
1 1 Alia 620 IT
2 2 Brijesh 440 Commerce
3 3 Yash 600 Humanities
4 4 Mallika 660 IT
5 5 Zayn 560 IT

Working with Excel Files in R Programming


Excel files are of extension .xls, .xlsx and .csv(comma-separated values). To
start working with excel files in R Programming Language , we need to first
import excel files in RStudio or any other R supporting IDE(Integrated
development environment).
Reading Excel Files in R Programming Language
First, install readxl package in R to load excel files. Various methods
including their subparts are demonstrated further.
Sample_data1.xlsx:
Sample_data2.xlsx:
Reading Files:
The two excel files Sample_data1.xlsx and Sample_data2.xlsx and read from
the working directory.

 R

# Working with Excel Files

# Installing required package

install.packages("readxl")

# Loading the package

library(readxl)
# Importing excel file

Data1 < - read_excel("Sample_data1.xlsx")

Data2 < - read_excel("Sample_data2.xlsx")

# Printing the data

head(Data1)

head(Data2)

The excel files are loaded into variables Data_1 and Data_2 as
a dataframes and then variable Data_1 and Data_2 is called that prints the
dataset.
Modifying Files
The Sample_data1.xlsx file and Sample_file2.xlsx are modified.

 R

# Modifying the files


Data1$Pclass <- 0

Data2$Embarked <- "S"

# Printing the data

head(Data1)

head(Data2)

The value of the P-class attribute or variable of Data1 data is modified to 0.


The value of Embarked attribute or variable of Data2 is modified to S.
Deleting Content from files
The variable or attribute is deleted from Data1 and Data2 datasets
containing Sample_data1.xlsx and Sample_data2.xlsx files.

 R
# Deleting from files

Data1 <- Data1[-2]

Data2 <- Data2[-3]

# Printing the data

Data1

Data2

The – sign is used to delete columns or attributes from the dataset. Column 2
is deleted from the Data1 dataset and Column 3 is deleted from the Data2
dataset.
Merging Files
The two excel datasets Data1 and Data2 are merged using merge() function
which is in base package and comes pre-installed in R.
 R
# Merging Files

Data3 <- merge(Data1, Data2, all.x = TRUE, all.y = TRUE)

# Displaying the data

head(Data3)

Data1 and Data2 are merged with each other and the resultant file is stored
in the Data3 variable.
Creating new columns
New columns or features can be easily created in Data1 and Data2 datasets.

 R

# Creating feature in Data1 dataset

Data1$Num < - 0

# Creating feature in Data2 dataset

Data2$Code < - "Mission"


# Printing the data

head(Data1)

head(Data2)

Num is a new feature that is created with 0 default value in Data1


dataset. Code is a new feature that is created with the mission as a default
string in Data2 dataset.
Writing Files
After performing all operations, Data1 and Data2 are written into new files
using write.xlsx() function built in writexl package.
 R

# Installing the package

install.packages("writexl")

# Loading package
library(writexl)

# Writing Data1

write_xlsx(Data1, "New_Data1.xlsx")

# Writing Data2

write_xlsx(Data2, "New_Data2.xlsx")
The Data1 dataset is written New_Data1.xlsx file and Data2 dataset is
written in New_Data2.xlsx file. Both the files are saved in the present
working directory.

Working with JSON Files in R Programming


JSON stands for JavaScript Object Notation. These files contain the data
in human readable format, i.e. as text. Like any other file, one can read as
well as write into the JSON files. In order to work with JSON files in R, one
needs to install the “rjson” package. The most common tasks done using
JSON files under rjson packages are as follows:
 Install and load the rjson package in R console
 Create a JSON file
 Reading data from JSON file
 Write into JSON file
 Converting the JSON data into Dataframes
 Working with URLs
Install and load the rjson package
One can install the rjson from the R console using
the install.packages() command in the following way:
install.packages("rjson")
After installing rjson package one has to load the package using
the library() function as follows:
library("rjson")
Creating a JSON file
To create a JSON file, one can do the following steps:
 Copy the data given below into a notepad file or any text editor file. One
can also create his own data as per the given format.
 {
 "ID":["1","2","3","4","5"],
 "Name":
["Mithuna","Tanushree","Parnasha","Arjun","Pankaj"],
 "Salary":["722.5","815.2","1611","2829","843.25"],
 "StartDate":
["6/17/2014","1/1/2012","11/15/2014","9/23/2013","5/21/2013
"],
 "Dept":["IT","IT","HR","Operations","Finance"]
}
 Choose “all types” as the file type and save the file with .json extension.
(Example: example.json)
 One must make sure that the information or data is contained within a pair
or curly braces { } .
Reading a JSON file
In R, reading a JSON file is quite a simple task. One can extract and read
the data of a JSON file very efficiently using the fromJSON() function.
The fromJSON() function takes the JSON file and returns the extracted data
from the JSON file in the list format by default.
Example:
Suppose the above data is stored in a file named example.json in the E
drive. To read the file we must write the following code.

# Read a JSON file

# Load the package required to read JSON files.

library("rjson")

# Give the input file name to the function.

result <- fromJSON(file = "E:\\example.json")

# Print the result.

print(result)

Output:
$ID
[1] "1" "2" "3" "4" "5"

$Name
[1] "Mithuna" "Tanushree" "Parnasha" "Arjun" "Pankaj"

$Salary
[1] "722.5" "815.2" "1611" "2829" "843.25"
$StartDate
[1] "6/17/2014" "1/1/2012" "11/15/2014" "9/23/2013"
"5/21/2013"

$Dept
[1] "IT" "IT" "HR" "Operations"
"Finance"

Writing into a JSON file


One need to create a JSON Object using toJSON() function before he writes
the data to a JSON file. To write into a JSON file use the write() function.
Example:

# Writing into JSON file.

# Load the package required to read JSON files.

library("rjson")

# creating the list

list1 <- vector(mode="list", length=2)

list1[[1]] <- c("sunflower", "guava", "hibiscus")

list1[[2]] <- c("flower", "fruit", "flower")

# creating the data for JSON file

jsonData <- toJSON(list1)


# writing into JSON file

write(jsonData, "result.json")

# Give the created file name to the function

result <- fromJSON(file = "result.json")

# Print the result

print(result)

Output:
[[1]]
[1] "sunflower" "guava" "hibiscus"

[[2]]
[1] "flower" "fruit" "flower"
Converting the JSON data into Dataframes
In R, to convert the data extracted from a JSON file into a data frame one
can use the as.data.frame() function.
Example:

# Convert the file into dataframe

# Load the package required to read JSON files.

library("rjson")
# Give the input file name to the function.

result <- fromJSON(file = "E://example.json")

# Convert JSON file to a data frame.

json_data_frame <- as.data.frame(result)

print(json_data_frame)

Output:
ID Name Salary StartDate Dept
1 1 Mithuna 722.5 6/17/2014 IT
2 2 Tanushree 815.2 1/1/2012 IT
3 3 Parnasha 1611 11/15/2014 HR
4 4 Arjun 2829 9/23/2013 Operations
5 5 Pankaj 843.25 5/21/2013 Finance
Working with URLs
One can take datasets from any websites and extract the data and use them.
This can be done under any of two packages,
namely RJSONIO and jsonlite.
Example:

# working with URLs

# import required library

library(RJSONIO)
# extracting data from the website

Raw <- fromJSON(

"https://data.ny.gov/api/views/9a8c-vfzj/rows.json?
accessType=DOWNLOAD")

# extract the data node

food_market <- Raw[['data']]

# assembling the data into data frames

Names <- sapply(food_market, function(x) x[[14]])

head(Names)

Output:
[1] "LUCKY MART " "CUMBERLAND FARMS 1587 "
[3] "K&M SPORTS " "MASON&OLD RIDGE FARM "
[5] "HAMPTON CHUTNEY CO " "CM - HUTCHINSON "

Functions in R Programming
Functions are useful when you want to perform a certain task multiple times.
A function accepts input arguments and produces the output by executing
valid R commands that are inside the function. In R Programming
Language when you are creating a function the function name and the file in
which you are creating the function need not be the same and you can have
one or more functions in R.
Table of Content
 Function in R Programming
 Types of Function in R Language
 Built-in Function in R Programming Language
 User-defined Functions in R Programming Language
 R Function Example
Function in R Programming
Functions are created in R by using the command function(). The general
structure of the function file is as follows:

Functions in R Programming

Note: In the above syntax f is the function name, this means that you are
creating a function with name f which takes certain arguments and executes
the following statements.
Types of Function in R Language
1. Built-in Function: Built-in functions in R are pre-defined functions that
are available in R programming languages to perform common tasks or
operations.
2. User-defined Function: R language allow us to write our own function.
Built-in Function in R Programming Language
Here we will use built-in functions like sum(), max() and min().
 R

# Find sum of numbers 4 to 6.

print(sum(4:6))

# Find max of numbers 4 and 6.

print(max(4:6))

# Find min of numbers 4 and 6.


print(min(4:6))

Output
[1] 15
[1] 6
[1] 4
Other Built-in Functions in R
Functions Syntax

Mathematical Functions

a. abs() calculates a number’s absolute value.

b. sqrt() calculates a number’s square root.

rounds a number to the nearest


c. round() integer.

calculates a number’s exponential


d. exp() value

which calculates a number’s natural


e. log() logarithm.

calculates a number’s cosine, sine,


f. cos(), sin(), and tan() and tang.

Statistical Functions

A vector’s arithmetic mean is


a. mean() determined by the mean() function.
Functions Syntax

A vector’s median value is


b. median() determined by the median() function.

calculates the correlation between


c. cor() two vectors.

calculates the variance of a vector


d. var() and calculates the standard deviation
of a vector.

Data Manipulation Functions

a. unique() returns the unique values in a vector.

subsets a data frame based on


b. subset() conditions.

groups data according to a grouping


c. aggregate() variable.

uses ascending or descending order


d. order() to sort a vector.

File Input/Output Functions

a. read.csv() reads information from a CSV file.

publishes information to write a CSV


b. Write.csv() file.
Functions Syntax

c. Read. table() reads information from a tabular.

d. Write.table() creates a tabular file with data.

User-defined Functions in R Programming Language


R provides built-in functions like print(), cat(), etc. but we can also create our
own functions. These functions are called user-defined functions.
Example
 R

# A simple R function to check

# whether x is even or odd

evenOdd = function(x){

if(x %% 2 == 0)

return("even")

else

return("odd")

print(evenOdd(4))

print(evenOdd(3))

Output
[1] "even"
[1] "odd"
R Function Example
Single Input Single Output
Now create a function in R that will take a single input and gives us a single
output.
Following is an example to create a function that calculates the area of a
circle which takes in the arguments the radius. So, to create a function,
name the function as “areaOfCircle” and the arguments that are needed to
be passed are the “radius” of the circle.
 R

# A simple R function to calculate

# area of a circle

areaOfCircle = function(radius){

area = pi*radius^2

return(area)

print(areaOfCircle(2))

Output
12.56637
Multiple Input Multiple Output
Now create a function in R Language that will take multiple inputs and gives
us multiple outputs using a list.
The functions in R Language take multiple input objects but returned only
one object as output, this is, however, not a limitation because you can
create lists of all the outputs which you want to create and once the list is
created you can access them into the elements of the list and get the
answers which you want.
Let us consider this example to create a function “Rectangle” which takes
“length” and “width” of the rectangle and returns area and perimeter of that
rectangle. Since R Language can return only one object. Hence, create one
object which is a list that contains “area” and “perimeter” and return the list.
 R

# A simple R function to calculate

# area and perimeter of a rectangle

Rectangle = function(length, width){

area = length * width

perimeter = 2 * (length + width)

# create an object called result which is

# a list of area and perimeter

result = list("Area" = area, "Perimeter" = perimeter)

return(result)

resultList = Rectangle(2, 3)

print(resultList["Area"])

print(resultList["Perimeter"])

Output
$Area
[1] 6
$Perimeter
[1] 10
Inline Functions in R Programming Language
Sometimes creating an R script file, loading it, executing it is a lot of work
when you want to just create a very small function. So, what we can do in
this kind of situation is an inline function.
To create an inline function you have to use the function command with the
argument x and then the expression of the function.
Example
 R

# A simple R program to

# demonstrate the inline function

f = function(x) x^2*4+x/3

print(f(4))

print(f(-2))

print(0)

Output
65.33333
15.33333
0
Passing Arguments to Functions in R Programming Language
There are several ways you can pass the arguments to the function:
 Case 1: Generally in R, the arguments are passed to the function in the
same order as in the function definition.
 Case 2: If you do not want to follow any order what you can do is you can
pass the arguments using the names of the arguments in any order.
 Case 3: If the arguments are not passed the default values are used to
execute the function.
Now, let us see the examples for each of these cases in the following R
code:
 R
# A simple R program to demonstrate

# passing arguments to a function

Rectangle = function(length=5, width=4){

area = length * width

return(area)

# Case 1:

print(Rectangle(2, 3))

# Case 2:

print(Rectangle(width = 8, length = 4))

# Case 3:

print(Rectangle())

Output
6
32
20
Lazy Evaluations of Functions in R Programming Language
In R the functions are executed in a lazy fashion. When we say lazy what it
means is if some arguments are missing the function is still executed as long
as the execution does not involve those arguments.
Example
In the function “Cylinder” given below. There are defined three-argument
“diameter”, “length” and “radius” in the function and the volume calculation
does not involve this argument “radius” in this calculation. Now, when you
pass this argument “diameter” and “length” even though you are not passing
this “radius” the function will still execute because this radius is not used in
the calculations inside the function.
Let’s illustrate this in an R code given below:
 R

# A simple R program to demonstrate

# Lazy evaluations of functions

Cylinder = function(diameter, length, radius ){

volume = pi*diameter^2*length/4

return(volume)

# This'll execute because this

# radius is not used in the

# calculations inside the function.

print(Cylinder(5, 10))

Output
196.3495
If you do not pass the argument and then use it in the definition of the
function it will throw an error that this “radius” is not passed and it is being
used in the function definition.
Example
 R
# A simple R program to demonstrate

# Lazy evaluations of functions

Cylinder = function(diameter, length, radius ){

volume = pi*diameter^2*length/4

print(radius)

return(volume)

# This'll throw an error

print(Cylinder(5, 10))

Output
Error in print(radius) : argument "radius" is missing, with
no default
Function Arguments in R Programming
 Read

 Discuss

 Courses

 Practice



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.
Adding Arguments in R
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.
Syntex:
function_name <- function(arg1, arg2, … )
{
code
}
Example:1
 R

calculate_square <- function(x) {

result <- x^2

return(result)

value1 <- 5

square1 <- calculate_square(value1)

print(square1)

value2 <- -2.5

square2 <- calculate_square(value2)

print(square2)

Output:
[1] 25
[1] 6.25
Example:2
 R

# Function definition

# To check n is divisible by 5 or not

divisbleBy5 <- function(n){

if(n %% 5 == 0)

return("number is divisible by 5")

else

return("number is not divisible by 5")

# Function call

divisbleBy5(100)

divisbleBy5(4)

divisbleBy5(20.0)

Output:
[1] "number is divisible by 5"
[1] "number is not divisible by 5"
[1] "number is divisible by 5"
Adding Multiple Arguments in R
A function in R programming can have multiple arguments too.
Below is an implementation of a function with multiple arguments.
Example:
 R

# Function definition

# To check a is divisible by b or not

divisible <- function(a, b){

if(a %% b == 0)

return(paste(a, "is divisible by", b))

else

return(paste(a, "is not divisible by", b))

# Function call

divisible(7, 3)

divisible(36, 6)

divisible(9, 2)
Output:
[1] "7 is not divisible by 3"
[1] "36 is divisible by 6"
[1] "9 is not divisible by 2"
Adding Default Value in R
The default value in a function is a value that is not required to
specify each time the function is called. If the value is passed by the
user, then the user-defined value is used by the function otherwise,
the default value is used. Below is an implementation of a function
with a default value.
Example:
 R

# Function definition to check

# a is divisible by b or not.

# If b is not provided in function call,

# Then divisibility of a is checked with 3 as default

divisible <- function(a, b = 3){

if(a %% b == 0)

return(paste(a, "is divisible by", b))

else

return(paste(a, "is not divisible by", b))

}
}

# Function call

divisible(10, 5)

divisible(12)

Output:
[1] "10 is divisible by 5"
[1] "12 is divisible by 3"
Dots Argument
Dots argument (…) is also known as ellipsis which allows the
function to take an undefined number of arguments. It allows the
function to take an arbitrary number of arguments. Below is an
example of a function with an arbitrary number of arguments.
Example:
 R

# Function definition of dots operator

fun <- function(n, ...){

l <- list(n, ...)

paste(l, collapse = " ")

# Function call

fun(5, 1L, 6i, TRUE, "GeeksForGeeks", "Dots operator")

Output:
[1] "5 1 0+6i TRUE GeeksForGeeks Dots operator"
Function as Argument
In R programming, functions can be passed to another functions as
arguments. Below is an implementation of function as an argument.
Example:
 R

# Function definition

# Function is passed as argument

fun <- function(x, fun2){

return(fun2(x))

# sum is built-in function

fun(c(1:10), sum)

# mean is built-in function

fun(rnorm(50), mean)

Output:
[1] 55
[1] 0.2153183
Types of Functions in R Programming
 Read

 Discuss

 Courses

 Practice



A function is a set of statements orchestrated together to perform a


specific operation. A function is an object so the interpreter is able
to pass control to the function, along with arguments that may be
necessary for the function to accomplish the actions. The function in
turn performs the task and returns control to the interpreter as well
as any return values that may be stored in other objects.

How to Define a Function?

In R programming, a function can be defined using the keyword


function. The syntax to define a function in R is as follows:

Syntax:

function_name = function(arg_1, arg_2, …)


{
Function body
}

The various components/parts of a function are:

 Function name: It 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. Whenever a function
is invoked, a value if passed to the argument.They are optional;
that is, a function may contain no arguments. Also arguments can
have default values.
 Function Body: It contains all the set of statements that defines
what actually the function does.
 Return Values: It is the values that function returns after the
successful execution of the tasks.In more general,it is the last
expression in the function body to be evaluated.

Calling a Function

It is nothing but calling the original function with a valid number of


arguments. A function can be called with an argument, without an
argument and with a default value as well.

Example: Calling a function without an argument

 r

# create a function cube

# without an argument

cube <- function()

for(i in 1:10)

print(i^3)

# calling function cube without an argument


cube()

Output:
[1] 1
[1] 8
[1] 27
[1] 64
[1] 125
[1] 216
[1] 343
[1] 512
[1] 729
[1] 1000
Example: Calling a function with an argument.
 r

# create a function factorial

# with a numeric argument n

factorial <- function(n)

if(n==0)

return(1)

else
{

return(n * factorial(n - 2))

# calling function cube with an argument

factorial(7)

Output:
[1] 5040
Example: Calling a function with default argument.
 r

# create a function def_arg

# without an argument

def_arg <- function(a = 23, b = 35)

output <- (a + b) * a + (a - b) * b

print(output)

# calling function def_arg without an argument


def_arg()

# call the function with giving new values of the argument.

def_arg(16, 22)

Output:
[1] 914
[1] 476

Types of Function

There are mainly three types of function in R programming:

1. Primitive Functions
2. Infix Functions
3. Replacement Functions

Primitive Functions
Generally, a function comprises of three parts:

 The formals(), the list of arguments that control how you call the
function.
 The body(), the code inside the function.
 The environment(), the data structure that determines how the
function finds the values associated with the names.
The formals and body are defined explicitly whenever one creates a
function, but the environment is specified implicitly, based on where
you define the function. But there is an exception to the rule that a
function has three components, some functions call C code directly.
These functions are known as primitive functions. Primitive functions
exist primarily in C, not R, so
their formals(), body(),and environment() are NULL. These
functions are only found in the base package. Primitive functions are
harder to write but are highly efficient. They are of two types, either
type builtin or type special.
 r

typeof(sum)

typeof('[')

[1] "builtin" #> typeof(sum)


[1] "character" #> typeof('[')
Example: To print the names of available primitive functions in your
R console run the following code.
 r

names(methods:::.BasicFunsList)

Output:
[1] "$" "$<-" "["
"[<-" "[[" "[[="
"cosh" "cummax" "dimnames<-"
[22] "as.raw" "log2" "tan"
"dim" "as.logical" "^"
"is.finite"
[29] "sinh" "log10"
"as.numeric" "dim<-" "is.array"
"tanpi" "gamma"
[36] "atan" "as.integer" "Arg"
"signif" "cumprod" "cos"
"length"
[43] "!=" "digamma" "exp"
"floor" "acos" "seq.int"
"abs"
[50] "length<-" "sqrt" "!"
"acosh" "is.nan" "Re"
"tanh"
[57] "names" "cospi" "&"
"anyNA" "trunc" "cummin"
"levels<-"
[64] "*" "Mod" "|"
"names<-" "+" "log"
"lgamma"
[71] "as.complex" "asinh" "-"
"sin" "/" "as.environment"
"<="
[78] "as.double" "is.infinite"
"is.numeric" "rep" "round"
"sinpi" "dimnames"
[85] "asin" "as.character" "%/%"
"is.na" "" "Im"
[92] "%%" "trigamma" "=="
"cumsum" "atanh" "sign"
"ceiling"
[99] "Conj" "as.call" "log1p"
"expm1" "(" ":"
"="
[106] "@" "{" "~"
"&&" ".C" "baseenv"
"quote"
[113] "<-" "is.name" "if"
"||" "attr<-" "untracemem"
".cache_class"
[120] "substitute" "interactive" "is.call"
"switch" "function" "is.single"
"is.null"
[127] "is.language" "is.pairlist"
".External.graphics" "globalenv" "class<-"
".Primitive" "is.logical"
[134] "enc2utf8" "UseMethod" ".subset"
"proc.time" "enc2native" "repeat"
"<<-"
[141] "@<-" "missing" "nargs"
"isS4" ".isMethodsDispatchOn" "forceAndCall"
".primTrace"
[148] "storage.mode<-" ".Call" "unclass"
"gc.time" ".subset2" "environment<-"
"emptyenv"
[155] "seq_len" ".External2"
"is.symbol" "class" "on.exit"
"is.raw" "for"
[162] "is.complex" "list"
"invisible" "is.character" "oldClass<-"
"is.environment" "attributes"
[169] "break" "return" "attr"
"tracemem" "next" ".Call.graphics"
"standardGeneric"
[176] "is.atomic" "retracemem"
"expression" "is.expression" "call"
"is.object" "pos.to.env"
[183] "attributes<-" ".primUntrace"
"...length" ".External" "oldClass"
".Internal" ".Fortran"
[190] "browser" "is.double" ".class2"
"while" "nzchar" "is.list"
"lazyLoadDBfetch"
[197] "...elt" "is.integer"
"is.function" "is.recursive" "seq_along"
"unlist" "as.vector"
[204] "lengths"
Infix Functions
Infix functions are those functions in which the function name comes
in between its arguments, and hence have two arguments. R comes
with a number of built-in infix operators such as :, ::, :::, $, @, ^, *,
/, +, -, >, >=, <, <=, ==, !=, !, &, &&, |, ||, ~, <-, and <<-.
One can create his own infix functions that start and end with %.
The name of an infix function is more flexible as it can contain any
sequence of characters except %. There are some predefined infix
operators in R programming.

Operators Description

%% Remainder operator

%/% Integer Division

%*% Matrix multiplication


Operators Description

%o% Outer Product

%x% Kronecker product

%in% Matching Operator

Example: Create a two argument function that gives greater of two


numbers and bind it to a name that starts and ends with %.

 r

# R program to illustrate

# Infix function

'%Greater%' <- function(a, b)

if(a > b) print(a)

else if(b > a) print(b)

else print("equal")

5 %Greater% 7

2300 %Greater% 67
Output:
[1] 7
[1] 2300
Replacement Functions
Replacement functions modify their arguments in place(modifying
an R object usually creates a copy). The name of replacement
functions are always succeeded by <. They must have arguments
named x and value, and return the modified object. In case of a
replacement, a function needs additional arguments, the additional
arguments should be placed between x and value, and must be
called with additional arguments on the left. The name of the
function has to be quoted as it is a syntactically valid but non-
standard name and the parser would interpret <- as the operator
not as part of the function name if it weren’t quoted.

Syntax:
“function_name<-” <- function(x, additional arguments, value)
{
function body
}

Example:

 r

# R program to illustrate

# Replacement function

"replace<-" <- function(x, value)

{
x[1] = value

x = rep.int(5, 7)

replace(x) = 0L

print(x)

Output:
[1] 0 5 5 5 5 5 5

Decision Making in R Programming – if, if-


else, if-else-if ladder, nested if-else, and
switch
 Read

 Discuss

 Courses

 Practice



Decision making is about deciding the order of execution of


statements based on certain conditions. In decision making
programmer needs to provide some condition which is evaluated by
the program, along with it there also provided some statements
which are executed if the condition is true and optionally other
statements if the condition is evaluated to be false.
The decision making statement in R are as followed:
 if statement
 if-else statement
 if-else-if ladder
 nested if-else statement
 switch statement
if statement
Keyword if tells compiler that this is a decision control instruction
and the condition following the keyword if is always enclosed within
a pair of parentheses. If the condition is TRUE the statement gets
executed and if condition is FALSE then statement does not get
executed.
Syntax:
if(condition is true){
execute this statement
}
Flow Chart:

Example:
 r

# R program to illustrate
# if statement

a <- 76

b <- 67

# TRUE condition

if(a > b)

c <- a - b

print("condition a > b is TRUE")

print(paste("Difference between a, b is : ", c))

# FALSE condition

if(a < b)

c <- a - b

print("condition a < b is TRUE")

print(paste("Difference between a, b is : ", c))

}
Output:
[1] "condition a > b is TRUE"
[1] "Difference between a, b is : 9"
if-else statement
If-else, provides us with an optional else block which gets executed
if the condition for if block is false. If the condition provided to if
block is true then the statement within the if block gets executed,
else the statement within the else block gets executed.
Syntax:
if(condition is true) {
execute this statement
} else {
execute this statement
}
Flow Chart:

Example :
 r
# R if-else statement Example

a <- 67

b <- 76

# This example will execute else block

if(a > b)

c <- a - b

print("condition a > b is TRUE")

print(paste("Difference between a, b is : ", c))

} else

c <- a - b

print("condition a > b is FALSE")

print(paste("Difference between a, b is : ", c))

Output:
[1] "condition a > b is FALSE"
[1] "Difference between a, b is : -9"
if-else-if ladder
It is similar to if-else statement, here the only difference is that an if
statement is attached to else. If the condition provided to if block is
true then the statement within the if block gets executed, else-if the
another condition provided is checked and if true then the
statement within the block gets executed.
Syntax:
if(condition 1 is true) {
execute this statement
} else if(condition 2 is true) {
execute this statement
} else {
execute this statement
}
Flow Chart:
Example :
 r

# R if-else-if ladder Example

a <- 67

b <- 76
c <- 99

if(a > b && b > c)

print("condition a > b > c is TRUE")

} else if(a < b && b > c)

print("condition a < b > c is TRUE")

} else if(a < b && b < c)

print("condition a < b < c is TRUE")

Output:
[1] "condition a < b < c is TRUE"
Nested if-else statement
When we have an if-else block as an statement within an if block or
optionally within an else block, then it is called as nested if else
statement. When an if condition is true then following child if
condition is validated and if the condition is wrong else statement is
executed, this happens within parent if condition. If parent if
condition is false then else block is executed with also may contain
child if else statement.
Syntax:
if(parent condition is true) {
if( child condition 1 is true) {
execute this statement
} else {
execute this statement
}
} else {
if(child condition 2 is true) {
execute this statement
} else {
execute this statement
}
}
Flow Chart:

Example:
 r

# R Nested if else statement Example


a <- 10

b <- 11

if(a == 10)

if(b == 10)

print("a:10 b:10")

} else

print("a:10 b:11")

} else

if(a == 11)

print("a:11 b:10")

} else
{

print("a:11 b:11")

Output:
[1] "a:10 b:11"
switch statement
In this switch function expression is matched to list of cases. If a
match is found then it prints that case’s value. No default case is
available here. If no case is matched it outputs NULL as shown in
example.
Syntax:
switch (expression, case1, case2, case3,…,case n )
Flow Chart :
Example:
 r

# R switch statement example

# Expression in terms of the index value

x <- switch(

2, # Expression

"Geeks1", # case 1

"for", # case 2

"Geeks2" # case 3

print(x)

# Expression in terms of the string value

y <- switch(

"GfG3", # Expression

"GfG0"="Geeks1", # case 1

"GfG1"="for", # case 2

"GfG3"="Geeks2" # case 3

print(y)
z <- switch(

"GfG", # Expression

"GfG0"="Geeks1", # case 1

"GfG1"="for", # case 2

"GfG3"="Geeks2" # case 3

print(z)

print(z)

Output:
[1] "for"
[1] "Geeks2"
NULL

For loop in R
 Read

 Discuss

 Courses

 Practice



For loop in R Programming Language is useful to iterate over


the elements of a list, data frame, vector, matrix, or any other
object. It means the for loop can be used to execute a group of
statements repeatedly depending upon the number of elements in
the object. 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.
For loop in R Syntax:
for (var in vector)
{
statement(s)
}
Here, var takes on each value of the vector during the loop. In each
iteration, the statements are evaluated.
Flowchart of For loop in R:

For loop in R

Iterating over a range in R – For loop

 R

# R Program to demonstrate
# the use of for loop

for (i in 1: 4)

print(i ^ 2)

Output:
[1] 1
[1] 4
[1] 9
[1] 16
In the above example, we iterated over the range 1 to 4 which was
our vector. Now there can be several variations of this general for
loop. Instead of using a sequence 1:5, we can use the concatenate
function as well.

Using concatenate function in R – For loop

 R

# R Program to demonstrate the use of

# for loop along with concatenate

for (i in c(-8, 9, 11, 45))

print(i)

Output:
[1] -8
[1] 9
[1] 11
[1] 45
Instead of writing our vector inside the loop, we can also define it
beforehand.

Using concatenate outside the loop R – For loop

 R

# R Program to demonstrate the use of

# for loop with vector

x <- c(-8, 9, 11, 45)

for (i in x)

print(i)

Output:
[1] -8
[1] 9
[1] 11
[1] 45
Nested For-loop in R
R programming language allows using one loop inside another loop.
In loop nesting, we can put any type of loop inside of any other type
of loop. For example, a for loop can be inside a while loop or vice
versa. The following section shows an example to illustrate the
concept:
Example:
 R

# R Program to demonstrate the use of

# nested for loop

for (i in 1:3)

for (j in 1:i)

print(i * j)

Output:
[1] 1
[1] 2
[1] 4
[1] 3
[1] 6
[1] 9
Jump Statements in R
We use a jump statement in loops to terminate the loop at a
particular iteration or to skip a particular iteration in the loop. The
two most commonly used jump statements in loops are:

Break Statement:

A break statement is a jump statement that is used to terminate the


loop at a particular iteration. The program then continues with the
next statement outside the loop(if any).
Example:
 R

# R Program to demonstrate the use of

# break in for loop

for (i in c(3, 6, 23, 19, 0, 21))

if (i == 0)

break

print(i)

print("Outside Loop")

Output:
[1] 3
[1] 6
[1] 23
[1] 19
[1] Outside loop
Here the loop exits as soon as zero is encountered.

Next Statement

It discontinues a particular iteration and jumps to the next iteration.


So when next is encountered, that iteration is discarded and the
condition is checked again. If true, the next iteration is executed.
Hence, the next statement is used to skip a particular iteration in
the loop.
Example:
 R

# R Program to demonstrate the use of

# next in for loop

for (i in c(3, 6, 23, 19, 0, 21))

if (i == 0)

next

print(i)

print('Outside Loop')

Output:
[1] 3
[1] 6
[1] 23
[1] 19
[1] 21
[1] Outside loop
Creating Multiple Plots within for-Loop in R

 R

# create a matrix of data


mat <- matrix(rnorm(100), ncol = 5)

# set up the plot layout

par(mfrow = c(2, 3))

# loop over columns of the matrix

for (i in 1:5) {

# create a histogram for each column

hist(mat[, i], main = paste("Column", i), xlab = "Values", col =


"lightblue")

Output:

For loop in R
In this example, the for loop iterates over the columns of the
matrix mat, and for each column, a histogram of the values is
created using the hist() function. The main argument of
the hist() function is used to set the title of each plot, and
the xlab argument is used to label the x-axis. The col argument is
used to set the color of the bars in the histogram to light blue.
The par() function is used to set up the plot layout with mfrow =
c(2, 3), which specifies that the plots should be arranged in 2 rows
and 3 columns. This means that the for loop will create 5 plots, each
of which is a histogram of one of the columns of the matrix mat,
arranged in a 2×3 grid.
Here as soon as zero is encountered, that iteration is discontinued
and the condition is checked again. Since 21 is not equal to 0, it is
printed. As we can conclude from the above two programs the basic
difference between the two jump statements is that the break
statement terminates the loop and the next statement skips a
particular iteration of the loop.

R – while loop
 Read

 Discuss

 Courses

 Practice



While loop in R programming language is used when the exact


number of iterations of a loop is not known beforehand. It executes
the same code again and again until a stop condition is met. While
loop checks for the condition to be true or false n+1 times rather
than n times. This is because the while loop checks for the condition
before entering the body of the loop.
R- While loop Syntax:
while (test_expression) {
statement
update_expression
}
How does a While loop execute?
 Control falls into the while loop.
 The flow jumps to Condition
 Condition is tested.
 If the Condition yields true, the flow goes into the Body.
 If the Condition yields false, the flow goes outside the
loop
 The statements inside the body of the loop get executed.
 Updation takes place.
 Control flows back to Step 2.
 The while loop has ended and the flow has gone outside.
Important Points about while loop in R language:
 It seems to be that while the loop will run forever but it is not
true, condition is provided to stop it.
 When the condition is tested and the result is false then the loop
is terminated.
 And when the tested result is True, then the loop will continue its
execution.
R – while loop Flowchart:

R – while loop

While Loop in R Programming Examples


Example 1:
 R
# R program to illustrate while loop

result <- c("Hello World")

i <- 1

# test expression

while (i < 6) {

print(result)

# update expression

i = i + 1

Output:
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
Example 2:
 R

# R program to illustrate while loop


result <- 1

i <- 1

# test expression

while (i < 6) {

print(result)

# update expression

i = i + 1

result = result + 1

Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
R – while loop break
Here we will use the break statement in the R programming
language. The break statement in R is used to bring the control out
of the loop when some external condition is triggered.

 R
# R program to illustrate while loop

result <- c("Hello World")

i <- 1

# test expression

while (i < 6) {

print(result)

if( i == 3){

break}

# update expression

i = i + 1

Output:
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
R – while loop next

 R
# Set an initial value for a variable

x <- 1

# Loop while x is less than 10

while (x < 10) {

if (x == 3) {

# Skip iteration when x is 3

x <- x + 1

next

print(paste("The current value of x is:", x))

x <- x + 1

# Print a message after the loop has finished

print("The loop has ended.")

Output
[1] "The current value of x is: 1"
[1] "The current value of x is: 2"
[1] "The current value of x is: 4"
[1] "The current value of x is: 5"
[1] "The current value of x is: 6"
[1] "The current value of x is: 7"
[1] "The current value of x is: 8"
[1] "The current value of x is: 9"
In this instance, x’s initial value is set to 1 at the beginning. Then, as
long as x is less than 10, we continue iterating using a while-loop.
We use an if statement inside the loop to see if x equals 3. If so, the
loop’s current iteration is skipped in favor of the following one using
the next statement. If not, we use the x – x + 1 expression to
increment x by 1 and output a message stating the current value of
x.
The next line instructs R to move on to the next iteration of the loop
and skip the current one. based on a condition, over a subset of the
loop’s iterations without ever leaving the loop.
R While Loop with If .. Else

 R

x <- 1

while (x <= 10) {

if (x %% 2 == 0) {

print(paste(x, "is even"))

} else {

print(paste(x, "is odd"))

x <- x + 1

Output
[1] "1 is odd"
[1] "2 is even"
[1] "3 is odd"
[1] "4 is even"
[1] "5 is odd"
[1] "6 is even"
[1] "7 is odd"
[1] "8 is even"
[1] "9 is odd"
[1] "10 is even"
In this illustration, we initialize a variable x to 1, and then we iterate
through the integers 1 through 10 using a while loop. We utilize an
if-else statement inside the loop to determine whether x is even or
odd. We publish a message stating that x is even if it is. We print a
message noting that x is unusual if it is. Then, until x is more than
10, we increase x by 1 and loop till x is greater than 10.

R – Repeat loop
 Read

 Discuss

 Courses

 Practice



Repeat loop in R is used to iterate over a block of code multiple


number of times. And also it executes the same code again and
again until a break statement is found.
Repeat loop, unlike other loops, doesn’t use a condition to exit the
loop instead it looks for a break statement that executes if a
condition within the loop body results to be true. An infinite loop in R
can be created very easily with the help of the Repeat loop. The
keyword used for the repeat loop is 'repeat'.
Syntax:
repeat {
commands
if(condition) {
break
}
}
Flowchart:

Example 1:

# R program to illustrate repeat loop

result <- c("Hello World")

i <- 1

# test expression

repeat {

print(result)
# update expression

i <- i + 1

# Breaking condition

if(i >5) {

break

Output:
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
Example 2:

# R program to illustrate repeat loop

result <- 1

i <- 1
# test expression

repeat {

print(result)

# update expression

i <- i + 1

result = result + 1

# Breaking condition

if(i > 5) {

break

Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

goto statement in R Programming


 Read

 Discuss

 Courses

 Practice



Goto statement in a general programming sense is a command that


takes the code to the specified line or block of code provided to it.
This is helpful when the need is to jump from one programming
section to the other without the use of functions and without
creating an abnormal shift.
Unfortunately, R doesn’t support goto but its algorithm can be easily
converted to depict its application. By using following methods this
can be carried out more smoothly:
 Use of if and else
 Using break, next and return
Flowchart

1. Goto encountered
2. Jump to the specified line number/ name of the code block
3. Execute code
Example 1: Program to check for even and odd numbers

a <- 4

if ((a %% 2) == 0)

print("even")

else
{

print("odd")

Output:
[1] "even"
Explanation:
 With goto:
1. Two blocks named EVEN and ODD
2. Evaluate for a
3. if even, goto block named EVEN
4. if odd, goto block named ODD
 Without goto:
1. Evaluate for a
2. if even, run the statement within if block
3. if odd, run the statement within else block
Example 2: Program to check for prime numbers

a <- 16

b <- a/2

flag <- 0

i <- 2

repeat

if ((a %% i)== 0)

flag <- 1
break

if (flag == 1)

print("composite")

else

print("prime")

Output:
[1] "composite"
Explanation:
 With goto :
1. This doesn’t require flag and if statement to check flag.
2. Evaluate for a
3. If a factor is found take the control to the line number that has
the print statement – print(“composite).
4. If not take it to the line number that has statement –
print(“prime”)
 Without goto:
1. Evaluate for a
2. If factor found, change flag
3. when the loop is complete check flag
4. Print accordingly
Note: Since R doesn’t have the concept of the goto statement, the
above examples were made using simple if-else and break
statements.

Break and Next statements in R


 Read

 Discuss

 Courses

 Practice



In R programming, we require a control structure to run a block of


code multiple times. Loops come in the class of the most
fundamental and strong programming concepts. A loop is a control
statement that allows multiple executions of a statement or a set of
statements. The word ‘looping’ means cycling or iterating.
Jump statements are used in loops to terminate the loop at a
particular iteration or to skip a particular iteration in the loop. The
two most commonly used jump statements in loops are:
 Break Statement
 Next Statement
Note: In R language continue statement is referred to as the next
statement.
The basic Function of Break and Next statement is to alter the
running loop in the program and flow the control outside of the loop.
In R language, repeat, for and while loops are used to run the
statement or get the desired output N number of times until the
given condition to the loop becomes false.
Sometimes there will be such a condition where we need to
terminate the loop to continue with the rest of the program. In such
cases R Break statement is used.
Sometimes there will be such condition where we don’t want loop to
perform the program for specific condition inside the loop. In such
cases, R next statement is used.
Break Statement
The break keyword is a jump statement that is used to terminate the
loop at a particular iteration.
Syntax:
if (test_expression) {
break
}
Example 1: Using break in For-loop

# R program for break statement in For-loop

no <- 1:10

for (val in no)

if (val == 5)

print(paste("Coming out from for loop Where i = ", val))

break

print(paste("Values are: ", val))

Output:
[1] "Values are: 1"
[1] "Values are: 2"
[1] "Values are: 3"
[1] "Values are: 4"
[1] "Coming out from for loop Where i = 5"
Example 2: Using break statement in While-loop

# R Break Statement Example

a<-1

while (a < 10)

print(a)

if(a==5)

break

a =a +1

Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Next Statement
The next statement is used to skip the current iteration in the loop
and move to the next iteration without exiting from the loop itself.
Syntax:
if (test_condition)
{
next
}
Example 1: Using next statement in For-loop
# R Next Statement Example

no <- 1:10

for (val in no)

if (val == 6)

print(paste("Skipping for loop Where i = ", val))

next

print(paste("Values are: ", val))

Output:
[1] "Values are: 1"
[1] "Values are: 2"
[1] "Values are: 3"
[1] "Values are: 4"
[1] "Values are: 5"
[1] "Skipping for loop Where i = 6"
[1] "Values are: 7"
[1] "Values are: 8"
[1] "Values are: 9"
[1] "Values are: 10"
Example 2: Using next statement in While-loop

# R Next Statement Example

x <- 1

while(x < 5)

x <- x + 1;

if (x == 3)

next;

print(x);

Output:
[1] 2
[1] 4
[1] 5

Handling Errors in R Programming


 Read

 Discuss

 Courses

 Practice



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
“warning.expression”. The basic functions that one can use for error
handling in the code :
 stop(…): It halts the evaluation of the current statement and
generates a message argument. The control is returned to the
top level.
 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.
 tryCatch(…): It helps to evaluate the code and assign the
exceptions.
Condition 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 :
 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.
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:
check = tryCatch({
expression
}, warning = function(w){
code that handles the warnings
}, error = function(e){
code that handles the errors
}, finally = function(f){
clean-up code
})
Example:
 R

# R program illustrating error handling

# Applying tryCatch

tryCatch(

# Specifying expression

expr = {

1 + 1

print("Everything was fine.")

},

# Specifying error message

error = function(e){

print("There was an error message.")

},

warning = function(w){

print("There was a warning message.")

},
finally = {

print("finally Executed")

Output:
[1] "Everything was fine."
[1] "finally Executed"
withCallingHandlers() 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.
Example:
 R

# R program illustrating error handling

# Evaluation of tryCatch

check <- function(expression){

withCallingHandlers(expression,

warning = function(w){

message("warning:\n", w)
},

error = function(e){

message("error:\n", e)

},

finally = {

message("Completed")

})

check({10/2})

check({10/0})

check({10/'noe'})

Output:
Decision handling or Condition handling is an important point in any
programming language. Most of the use cases result in either positive or
negative results. Sometimes there is the possibility of condition checking of
more than one possibility and it lies with n number of possibilities. In this
article let’s discuss how condition handling works in R language.
Communicating Potential Problems
Developers always write good code to achieve good results. Not all problems
are unexpected. Few expected potential problems are,
 Giving the wrong type of input for a variable. In the place of numbers, we
are giving alphanumeric values,
 While uploading a file, non-existence of a file in the mentioned location,
 The resultant output after calculating some value is expected as a
numeric but the original output is either empty or null or invalid
During these scenarios, there are possibilities of going wrong with R
Code. And via errors, warnings, and messages they can be
communicated. Fatal errors are raised by stop() and force all execution to
terminate. Errors are used when there is no way for a function to
continue. Warnings are generated by warning() and are used to display
potential problems, such as when some elements of a vectorized input are
invalid, like log(-1:2). Messages are generated by message() and are used
to give informative output in a way that can easily be suppressed by the
user.
Handling Conditions Programmatically
In the R language, there are three different tools that are there for handling
conditions including errors programmatically. try() gives you the ability to
continue execution even when an error occurs.
Example:
 R

success <- try(100 + 200)

failure <- try("100" + "200")

Output:
Error in "100" + "200" : non-numeric argument to binary
operator

 R

# Class of success

class(success)

[1] "numeric"

 R

# Class of failure

class(failure)

[1] "try-error"
When we put the code inside the try block, code executes, even error occurs,
and also for correct results, it will be the last result evaluated, and if a failure,
it will give with “try-error”. tryCatch() specifies handler functions that control
what happens when a condition is signaled. One can take different actions
for warnings, messages, and interrupts.
Example:
 R

# Using tryCatch()

display_condition <- function(inputcode)

tryCatch(inputcode,

error = function(c) "Unexpected error occurred",

warning = function(c) "warning message, but

still need to look into code",

message = function(c) "friendly message, but

take precautions")

# Calling the function

display_condition(stop("!"))

display_condition(warning("?!"))

display_condition(message("?"))

display_condition(10000)

For Input:
display_condition(stop("!"))
Output:
[1] "Unexpected error occurred"
For Input:
display_condition(warning("?!"))
Output:
[1] "warning message, but still need to look into code"
For Input:
display_condition(message("?"))
Output:
[1] "friendly message, but take precautions"
For Input:
display_condition(10000)
Output:
[1] 10000
withCallingHandlers() is an alternative to tryCatch(). It establishes local
handlers, whereas tryCatch() registers existing handlers. This will be most
useful to handle a message with withCallingHandlers() rather
than tryCatch() since the latter will stop the program.
Example:
 R

# Using tryCatch()

message_handler <- function(c) cat("Important message is caught!\n")

tryCatch(message = message_handler,

message("1st value printed?")

message("Second value too printed!")

})

Output:
Important message is caught!

 R

# Using withCallingHandlers()

message_handler <- function(c) cat("Important message is caught!\n")


withCallingHandlers(message = message_handler,

message("1st value printed?")

message("Second value too printed!")

})

Output:
Important message is caught!
1st value printed?
Important message is caught!
Second value too printed!
Custom Signal Classes
One of the challenges of error handling in R is that most functions just
call stop() with a string. For example, “expected” errors (like a model failing
to converge for some input datasets) can be silently ignored, while
unexpected errors (like no disk space available) can be propagated to the
user.
Example:
 R

# R program to illustrate

# Custom signal classes

condition <- function(subclass, message,

call = sys.call(-1), ...) {

structure(

class = c(subclass, "condition"),


list(message = message, call = call),

...

is.condition <- function(x) inherits(x, "condition")

e <- condition(c("my_error", "error"),

"Unexpected error occurred")

stop(e) # Output as Unexpected error occurred

# comment out stop(e)

w <- condition(c("my_warning", "warning"),

"Appropriate warning!!!!")

warning(w) # Output as Appropriate warning!!!!

# as well as Important message to be noted!!

# will be printed

m <- condition(c("my_message", "message"),

"Important message to be noted!!!")

message(m) # Output as Important message to be noted!!!


Output:
Error: Unexpected error occurred
Execution halted
But at the same time, if stop(e) line is commented out, both warning
and message are printed.
Warning message:
Appropriate warning!!!!
Important message to be noted!!
And if warning(w) is commented out, then
Important message to be noted!!
So by using custom signal classes, we can differentiate the errors. We can
see that in detail below
Example:
 R

# R program to illustrate

# Custom signal classes

condition <- function(subclass, message,

call = sys.call(-1), ...) {

structure(

class = c(subclass, "condition"),

list(message = message, call = call),

...

is.condition <- function(x) inherits(x, "condition")


custom_stop <- function(subclass, message,

call = sys.call(-1),

...) {

c <- condition(c(subclass, "error"), message,

call = call, ...)

stop(c)

check_log <- function(x) {

if (!is.numeric(x))

custom_stop("invalid_class",

"check_log() needs numeric input")

if (any(x < 0))

custom_stop("invalid_value",

"check_log() needs positive inputs")

log(x)

tryCatch(

check_log("ant"), # As we pass "ant", we will


# get Numeric inputs

# only are allowed as output

# for input, if we give with negative value

# let us check what happens,

# for that uncomment below line and see,

# obviously you get Positive

# numeric value need to be provided

#check_log("-100"),

invalid_class = function(c) "Numeric inputs

only are allowed",

invalid_value = function(c) "Positive numeric value

need to be provided"

Output:
[1] "Numeric inputs only are allowed"
But at the same time, when we passed check_log(“100”),
[1] "Only positive values are allowed"

Debugging in R Programming



Debugging is a process of cleaning a program code from bugs to run
it successfully. While writing codes, some mistakes or problems
automatically appears after the compilation of code and are harder
to diagnose. So, fixing it takes a lot of time and after multiple levels
of calls.
Debugging in R is through warnings, messages, and errors.
Debugging in R means debugging functions. Various debugging
functions are:
 Editor breakpoint
 traceback()
 browser()
 recover()
Editor Breakpoints
Editor Breakpoints can be added in RStudio by clicking to the left of
the line in RStudio or pressing Shift+F9 with the cursor on your
line. A breakpoint is same as browser() but it doesn’t involve
changing codes. Breakpoints are denoted by a red circle on the left
side, indicating that debug mode will be entered at this line after the
source is run.

traceback() Function
The traceback() function is used to give all the information on how
your function arrived at an error. It will display all the functions
called before the error arrived called the “call stack” in many
languages, R favors calling traceback.
Example:

# Function 1

function_1 <- function(a){

a +5

}
# Function 2

function_2 <- function(b) {

function_1(b)

# Calling function

function_2("s")

# Call traceback()

traceback()

Output:
2: function_1(b) at #1
1: function_2("s")
traceback()function displays the error during evaluations. The call
stack is read from the function that was run(at the bottom) to the
function that was running(at the top). Also we can use traceback() as
an error handler which will display error immediately without calling
of traceback.

# Function 1

function_1 <- function(a){

a +5

}
# Function 2

function_2 <- function(b){

function_1(b)

# Calling error handler

options(error = traceback)

function_2("s")

Output:
Error in a + 5 : non-numeric argument to binary operator
2: function_1(b) at #1
1: function_2("s")
browser() Function
browser() function is inserted into functions to open R interactive
debugger. It will stop the execution of function() and you can
examine the function with the environment of itself. In debug mode,
we can modify objects, look at the objects in the current
environment, and also continue executing.
Example:

browser[1]> command in consoles confirms that you are in debug


mode. Some commands to follow:
 ls(): Objects available in current environment.
 print(): To evaluate objects.
 n: To examine the next statement.
 s: To examine the next statement by stepping into function calls.
 where: To print a stack trace.
 c: To leave debugger and continue with execution.
 C: To exit debugger and go back to R prompt.
Also, debug() statement automatically inserts browser() statement at
the beginning of the function.
recover() Function
recover() statement is used as an error handler and not like the
direct statement. In recover(), R prints the whole call stack and lets
you select which function browser you would like to enter. Then
debugging session starts at the selected location.
Example:

# Calling recover

options(error = recover)

# Function 1

function_1 <- function(a){


a +5

# Function 2

function_2 <- function(b) {

function_1(b)

# Calling function

function_2("s")

Output:
Enter a frame number, or 0 to exit

1: function_2("s")
2: #2: function_1(b)

Selection:
The debugging session starts at the selected location.

You might also like