R Programming UNIT 2
R Programming UNIT 2
Example:
R
# 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
# 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
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
library(readr)
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
# Using read.delim()
myData = read.delim("http://www.sthda.com/upload/boxplot_format.txt")
print(head(myData))
Output:
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
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
R
library("xlsx")
write.xlsx(my_data, file = "result.xlsx",
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:
print(csv_data)
print (ncol(csv_data))
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:
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.
print (new_csv)
Output:
write.csv(new_csv, "new_sample.csv")
print(new_data)
Output:
print(new_data)
Output:
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>
library("XML")
library("methods")
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
library("XML")
library("methods")
# the contents of sample.xml are parsed
library("XML")
library("methods")
print (second_node)
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
library("XML")
library("methods")
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
R
install.packages("readxl")
library(readxl)
# Importing excel file
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
head(Data1)
head(Data2)
R
# Deleting from files
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
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
Data1$Num < - 0
head(Data1)
head(Data2)
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.
library("rjson")
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"
library("rjson")
write(jsonData, "result.json")
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:
library("rjson")
# Give the input file name to the function.
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:
library(RJSONIO)
# extracting data from the website
"https://data.ny.gov/api/views/9a8c-vfzj/rows.json?
accessType=DOWNLOAD")
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
print(sum(4:6))
print(max(4:6))
Output
[1] 15
[1] 6
[1] 4
Other Built-in Functions in R
Functions Syntax
Mathematical Functions
Statistical Functions
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
# 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
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
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
return(area)
# Case 1:
print(Rectangle(2, 3))
# Case 2:
# 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
volume = pi*diameter^2*length/4
return(volume)
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
volume = pi*diameter^2*length/4
print(radius)
return(volume)
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
return(result)
value1 <- 5
print(square1)
print(square2)
Output:
[1] 25
[1] 6.25
Example:2
R
# Function definition
if(n %% 5 == 0)
else
# 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
if(a %% b == 0)
else
# 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
# a is divisible by b or not.
if(a %% b == 0)
else
}
}
# 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 call
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
return(fun2(x))
fun(c(1:10), sum)
fun(rnorm(50), mean)
Output:
[1] 55
[1] 0.2153183
Types of Functions in R Programming
Read
Discuss
Courses
Practice
Syntax:
Calling a Function
r
# without an argument
for(i in 1:10)
print(i^3)
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
if(n==0)
return(1)
else
{
factorial(7)
Output:
[1] 5040
Example: Calling a function with default argument.
r
# without an argument
output <- (a + b) * a + (a - b) * b
print(output)
def_arg(16, 22)
Output:
[1] 914
[1] 476
Types of Function
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('[')
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
r
# R program to illustrate
# Infix function
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
{
x[1] = value
x = rep.int(5, 7)
replace(x) = 0L
print(x)
Output:
[1] 0 5 5 5 5 5 5
Discuss
Courses
Practice
Example:
r
# R program to illustrate
# if statement
a <- 76
b <- 67
# TRUE condition
if(a > b)
c <- a - b
# FALSE condition
if(a < b)
c <- a - b
}
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
if(a > b)
c <- a - b
} else
c <- a - b
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
a <- 67
b <- 76
c <- 99
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
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
x <- switch(
2, # Expression
"Geeks1", # case 1
"for", # case 2
"Geeks2" # case 3
print(x)
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
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.
R
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.
R
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
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:
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
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
for (i in 1:5) {
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
R – while loop
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
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
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
if (x == 3) {
x <- x + 1
next
x <- x + 1
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
if (x %% 2 == 0) {
} else {
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
Example 1:
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:
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
Discuss
Courses
Practice
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.
Discuss
Courses
Practice
no <- 1:10
if (val == 5)
break
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
a<-1
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
if (val == 6)
next
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
x <- 1
while(x < 5)
x <- x + 1;
if (x == 3)
next;
print(x);
Output:
[1] 2
[1] 4
[1] 5
Discuss
Courses
Practice
# Applying tryCatch
tryCatch(
# Specifying expression
expr = {
1 + 1
},
error = function(e){
},
warning = function(w){
},
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
# Evaluation of tryCatch
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
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()
tryCatch(inputcode,
take precautions")
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()
tryCatch(message = message_handler,
})
Output:
Important message is caught!
R
# Using withCallingHandlers()
})
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
structure(
...
"Appropriate warning!!!!")
# will be printed
# R program to illustrate
structure(
...
call = sys.call(-1),
...) {
stop(c)
if (!is.numeric(x))
custom_stop("invalid_class",
custom_stop("invalid_value",
log(x)
tryCatch(
#check_log("-100"),
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
a +5
}
# Function 2
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
a +5
}
# Function 2
function_1(b)
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:
# Calling recover
options(error = recover)
# Function 1
# Function 2
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.