[Go to site: main page, start]

0% found this document useful (0 votes)
12 views65 pages

Introduction to R Programming Basics

This document provides an introduction to R programming, covering its syntax, basic concepts, and applications in data science, statistical computing, and machine learning. It discusses the advantages and disadvantages of R, along with its data structures, operators, and how to write and execute R programs. Additionally, it includes examples of R code, variable assignments, and data manipulation techniques.

Uploaded by

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

Introduction to R Programming Basics

This document provides an introduction to R programming, covering its syntax, basic concepts, and applications in data science, statistical computing, and machine learning. It discusses the advantages and disadvantages of R, along with its data structures, operators, and how to write and execute R programs. Additionally, it includes examples of R code, variable assignments, and data manipulation techniques.

Uploaded by

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

59

UNIT- IV
R PROGRAMMING
4.1 INTRODUCTION
This chapter discusses the concept of R programming, to write a R program we
need to know the syntax of R. so we will discuss here about basic rules and syntax
to write a R program.
4.2 OBJECTIVES
The objective of this Unit is to make the student learns the basic concepts of R
programming like R syntax, objects and assignment, Arrays and matrices, Lists and
data frames, Grouping, loops and conditional execution and functions
4.3 CONTENTS
4.3.1 INTRODUCTION TO R
What is R?
R is a programming language and environment commonly used in statistical
computing, data analytics and scientific research.
It is one of the most popular languages used by statisticians, data analysts,
researchers and marketers to retrieve, clean, analyze, visualize and present data.
Due to its expressive syntax and easy-to-use interface, it has grown in
popularity in recent years.
Advantages of R
 Basically, it is most comprehensive statistical analysis package. As new
technology and ideas often appear first in R.
 As R is open-source software. Hence anyone can use and change it.
 It is an open source. We can run R anywhere and at any time, and also even sell
it under conditions of the license.
 As we know that R is good for GNU/Linux and Microsoft Windows. Also, it is
having a cross-platform which runs on many operating systems.
 Anyone can perform bug fixing, code enhancements, and new packages.
Disadvantages of R
 In R, quality of some packages is less than perfect.
 In R, no one to complain, if something doesn’t work.
 It is a software Application. Hence, many people devote their own time to
developing.
 Moreover, R can consume all available memory because of its memory
management.
Applications of R Programming in Real World
Data Science
`Data Science is a branch of study which involves obtaining meaningful
insights from raw & unstructured data. The colossal amount of data is processed
through programming, analytical & business skills.
Data Science is a multi- disciplinary field that uses scientific methods,
processes, algorithms to produce knowledge & insights from structured &
60

unstructured data. It utilises techniques & theories derived from many fields such
as computer science, mathematics, statistics & information science.
Programming languages like R give a data scientist superpower that allow
them to collect data in realtime, perform statistical and predictive analysis, create
visualizations and communicate actionable results to stakeholders. Most courses
on data science include R in their curriculum because it is the data scientist’s
favorite tool.
Statistical computing
Computational statistics, or statistical computing, is the interface between
statistics and computer science. It is the area of computational science (or scientific
computing) specific to the mathematical science of statistics.
R is the most popular programming language among statisticians. In fact, it
was initially built by statisticians for statisticians. R also has charting capabilities,
which means you can plot your data and create interesting visualizations from any
dataset.
Machine Learning
Machine Learning is a sub-area of artificial intelligence, whereby the term
refers to the ability of IT systems to independently find solutions to problems by
recognizing patterns in databases. In other words: Machine Learning enables IT
systems to recognize patterns on the basis of existing algorithms and data sets and
to develop adequate solution concepts. Therefore, in Machine Learning, artificial
knowledge is generated on the basis of experience.
R has found a lot of use in predictive analytics and machine learning. It has
various packages for common ML tasks like linear and non-linear regression,
decision trees, linear and non-linear classification and many more. Everyone from
machine learning enthusiasts to researchers use R to implement machine learning
algorithms in fields like finance, genetics research, retail, marketing and health
care.
First R Program
As a convention, our first R program will be the “Hello World!” program. We
can run our R program either at R command prompt or we can use an R script file.
Let’s see both one by one.
To start your R program in Windows, just open the RStudio app. This will start
the R Studio and you will get the prompt > in console, where you can start typing
your program.
Program:
Program to print “Hello World!” in the command prompt:
>helloStr <- "Hello World!"
> print ( helloStr)
Here the first statement defines a string variable helloStr where we assign
“Hello World!” and then next statement print() is being used to print the value
stored in variable helloStr. The output of the program is shown in the figure 3.1.
61

Figure 3.1 Sample R Program


R Script File
We can also use script files to write our program and then execute this script
file at your command prompt with the help of R interpreter called Rscript. First of
all, write the below code in a text file using any text editor like notepad and then
save this file with the .R extension. Such as hello.R; if you do not set the
environment variable, then you have to save this file in the bin folder of R.
Program:
# My first Hello World program in R Programming
helloStr <- "Hello World!"
print ( helloStr)
To execute this script file use the following command at your command
prompt. If you are using Linux or another operating system, the syntax will remain
the same. The method to run the script and its output are shown in the figure 3.2.

Figure 3.2 Sample R script Program execution

4.3.2 R PRELIMINARIES
R Reserved Words
Reserved words in R programming are a set of words that have special
meaning and cannot be used as an identifier (variable name, function name etc.).
This list of reserved words can be viewed by typing help (reserved) or ?
reserved at the R command prompt.
62

R Variables and Constants


Variable: Variables are used to store data, whose value can be changed
according to our need. Unique name given to variable (function and objects as well)
is identifier.
Constant: Constants, as the name suggests, are entities whose value cannot
be altered. Basic types of constant are numeric constants and character constants.
Numeric Constants
All numbers fall under this category. They can be of type integer, double or
complex. It can be checked with the typeof() function.
Numeric constants followed by L are regarded as integer and those followed by
i are regarded as complex.
Character Constants
Character constants can be represented using either single quotes (') or double
quotes (") as delimiters.
Variable Assignment
The variables can be assigned values using leftward, rightward and equal to
operator. The values of the variables can be printed using print() or cat() function.
The cat() function combines multiple items into a continuous print output.
The example program and its output is shown in the below figure.

Data Type of a Variable


In R, a variable itself is not declared of any data type, rather it gets the data
type of the R - object assigned to it. So R is called a dynamically typed language,
which means that we can change a variable’s data type of the same variable again
and again when using it in a program. The example is shown below.

Finding Variables
To know all the variables currently available in the workspace we use the ls()
function. Also the ls() function can use patterns to match the variable names.
print(ls()) will give all the variables currently available in the workspace.
63

Deleting Variables
Variables can be deleted by using the rm() function. Below we delete the
variable var.3. On printing the value of the variable error is thrown.
rm(var.3)
print(var.3)
When we execute the above code, it produces the following result
[1] "var.3"
Error in print(var.3) : object 'var.3' not found
All the variables can be deleted by using the rm() and ls() function together.
rm(list = ls())
print(ls())
When we execute the above code, it produces the following result
character(0)
R Operators
R has many operators to carry out different mathematical and logical
operations. Operators in R can mainly be classified into the following categories.
Arithmatic operators
Relational operators
Logical operators
Assignment operators
Arithmetic Operators
These operators are used to carry out mathematical operations like addition
and multiplication. Here is a list of arithmetic operators available in R.
Operator Description
+ Addition
– Subtraction
* Multiplication
/ Division
^ Exponent
%% Modulus (Remainder from division)
%/% Integer Division
Example
> x <- 5
> y <- 16
> x+y
[1] 21

> x-y
[1] -11
64

> x*y
[1] 80

> y/x
[1] 3.2
> y%/%x
[1] 3

> y%%x
[1] 1
> y^x
[1] 1048576
Relational Operators
Relational operators are used to compare between values. Here is a list of
relational operators available in R.
Operator Description
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
Example
> x <- 5
> y <- 16
> x<y
[1] TRUE

> x>y
[1] FALSE

> x<=5
[1] TRUE

> y>=20
[1] FALSE

> y == 16
[1] TRUE

> x != 5
[1] FALSE
Logical Operators
Logical operators are used to carry out Boolean operations like AND, OR etc.
65

Operator Description
! Logical NOT
& Element-wise logical AND
&& Logical AND
| Element-wise logical OR
|| Logical OR
Operators & and | perform element-wise operation producing result having
length of the longer operand. But && and || examines only the first element of the
operands resulting into a single length logical vector.
Zero is considered FALSE and non-zero numbers are taken as TRUE. An
example run.
> x <- c(TRUE,FALSE,0,6)
> y <- c(FALSE,TRUE,FALSE,TRUE)
> !x
[1] FALSE TRUE TRUE FALSE

> x&y
[1] FALSE FALSE FALSE TRUE
> x&&y
[1] FALSE
> x|y
[1] TRUE TRUE FALSE TRUE

> x||y
[1] TRUE
Assignment Operators
These operators are used to assign values to variables and these operators are
shown below.
Operator Description
<-, <<-, = Leftwards assignment
->, ->> Rightwards assignment
The operators <- and = can be used, almost interchangeably, to assign to
variable in the same environment.
The <<- operator is used for assigning to variables in the parent environments
(more like global assignments). The rightward assignments, although available are
rarely used.
> x <- 5
>x
[1] 5
>x=9
>x
[1] 9
> 10 -> x
>x
[1] 10
66

4.3.3 DATA STRUCTURES IN R


To make the best of the R language, you'll need a strong understanding of the
basic data types and data structures and how to operate on those. Very important
to understand because these are the things you will manipulate on a day-to-day
basis in R.
Everything in R is an object and it has 5 basic atomic classes. They are
logical (e.g., TRUE, FALSE)
integer (e.g,, 2L, [Link](3))
numeric (real or decimal) (e.g, 2, 2.0, pi)
complex (e.g, 1 + 0i, 1 + 4i)
character (e.g, "a", "swc")
R also has many data structures. These include
vector
list
matrix
data frame
factors (we will avoid these, but they have their uses)
tables
VECTOR
Vector is a basic data structure in R. It contains element of the same type.
The data types can be logical, integer, double, character, complex or raw.
A vector’s type can be checked with the typeof() function. Another important
property of a vector is its length. This is the number of elements in the vector and
can be checked with the function length().
Creating a vector in R
Vectors are generally created using the c() function. Since, a vector must have
elements of the same type, this function will try and coerce elements to the same
type, if they are different. Coercion is from lower to higher types from logical to
integer to double to character.
> x <- c(1, 5, 4, 9, 0)
> typeof(x)
[1] "double"

> length(x)
[1] 5

> x <- c(1, 5.4, TRUE, "hello")


>x
[1] "1" "5.4" "TRUE" "hello"
> typeof(x)
[1] "character"
67

If we want to create a vector of consecutive numbers, the: operator is very


helpful.
Creating a vector using: operator
> x <- 1:7; x
[1] 1 2 3 4 5 6 7

> y <- 2:-2; y


[1] 2 1 0 -1 -2
More complex sequences can be created using the seq() function, like defining
number of points in an interval, or the step size.
Creating a vector using seq() function
> seq(1, 3, by=0.2) # specify step size
[1] 1.0 1.2 1.4 1.6 1.8 2.0 2.2 2.4 2.6 2.8 3.0

> seq(1, 5, [Link]=4) # specify length of the vector


[1] 1.000000 2.333333 3.666667 5.000000
Accessing Elements of a Vector
Elements of a vector can be accessed using vector indexing. The vector used
for indexing can be logical, integer or character vector.
Using integer vector as index
Vector index in R starts from 1, unlike most programming languages where
index start from 0. We can use a vector of integers as index to access specific
elements. We can also use negative integers to return all elements except that those
specified. But we cannot mix positive and negative integers while indexing and real
numbers, if used, are truncated to integers.
>x
[1] 0 2 4 6 8 10

> x[3] # access 3rd element


[1] 4

> x[c(2, 4)] # access 2nd and 4th element


[1] 2 6

> x[-1] # access all but 1st element


[1] 2 4 6 8 10

> x[c(2, -4)] # cannot mix positive and negative integers


68

Error in x[c(2, -4)] : only 0's may be mixed with negative subscripts

> x[c(2.4, 3.54)] # real numbers are truncated to integers


[1] 2 4
Using character vector as index
This type of indexing is useful when dealing with named vectors. We can name
each elements of a vector.
> x <- c("first"=3, "second"=0, "third"=9)
> names(x)
[1] "first" "second" "third"
> x["second"]
second
0
> x[c("first", "third")]
first third
3 9
Modifying a vector in R
We can modify a vector using the assignment operator. We can use the
techniques discussed above to access specific elements and modify them. If we
want to truncate the elements, we can use reassignments.
>x
[1] -3 -2 -1 0 1 2
> x[2] <- 0; x # modify 2nd element
[1] -3 0 -1 0 1 2

> x[x<0] <- 5; x # modify elements less than 0


[1] 5 0 5 0 1 2

> x <- x[1:4]; x # truncate x to first 4 elements


[1] 5 0 5 0
How to delete a Vector?
We can delete a vector by simply assigning a NULL to it.
>x
[1] -3 -2 -1 0 1 2

> x <- NULL


>x
NULL

> x[4]
NULL
69

LISTS
List is a data structure having components of mixed data types. A vector
having all elements of the same type is called atomic vector but a vector having
elements of different type is called list. We can check if it’s a list with typeof()
function and find its length using length(). Here is an example of a list having three
components each of different data type.
>x
$a
[1] 2.5
$b
[1] TRUE
$c
[1] 1 2 3

> typeof(x)
[1] "list"

> length(x)
[1] 3
Creating a list in R
List can be created using the list() function.
> x <- list("a" = 2.5, "b" = TRUE, "c" = 1:3)
Here, we create a list x, of three components with data types double, logical
and integer vector respectively.
Its structure can be examined with the str() function.
> str(x)
List of 3
$ a: num 2.5
$ b: logi TRUE
$ c: int [1:3] 1 2 3
In this example, a, b and c are called tags which makes it easier to reference
the components of the list. However, tags are optional. We can create the same list
without the tags as follows. In such scenario, numeric indices are used by default
> x <- list(2.5,TRUE,1:3)
>x
[[1]]
[1] 2.5
70

[[2]]
[1] TRUE
[[3]]
[1] 1 2 3
Accessing components of a list
Lists can be accessed in similar fashion to vectors. Integer, logical or character
vectors can be used for indexing. Let us consider a list as follows.
>x
$name
[1] "John"
$age
[1] 19
$speaks
[1] "English" "French"

> x[c(1:2)] # index using integer vector


$name
[1] "John"
$age
[1] 19

> x[-2] # using negative integer to exclude second component


$name
[1] "John"
$speaks
[1] "English" "French"

> x[c(T,F,F)] # index using logical vector


$name
[1] "John"

> x[c("age","speaks")] # index using character vector


$age
[1] 19
$speaks
71

[1] "English" "French"


Indexing with [as shown above will give us sublist not the content inside the
component. To retrieve the content, we need to use [[. However, this approach will
allow us to access only a single component at a time.
> x["age"]
$age
[1] 19

> typeof(x["age"]) # single [ returns a list


[1] "list"

> x[["age"]] # double [[ returns the content


[1] 19

> typeof(x[["age"]])
[1] "double"

An alternative to [[, which is used often while accessing content of a list is the
$ operator. They are both the same except that $ can do partial matching on tags.
> x$name # same as x[["name"]]
[1] "John"

> x$a # partial matching, same as x$ag or x$age


[1] 19

> x[["a"]] # cannot do partial match with [[


NULL

> # indexing can be done recursively


> x$speaks[1]
[1] "English"

> x[["speaks"]][2]
[1] "French"
Modifying a list in R
We can change components of a list through reassignment. We can choose any
of the component accessing techniques discussed above to modify it. Notice below
that modification causes reordering of components.
> x[["name"]] <- "Clair"; x
$age
72

[1] 19
$speaks
[1] "English" "French"
$name
[1] "Clair"
Adding components to a list
Adding new components is easy. We simply assign values using new tags and
it will pop into action.
> x[["married"]] <- FALSE
>x
$age
[1] 19
$speaks
[1] "English" "French"
$name
[1] "Clair"
$married
[1] FALSE
Deleting components from a list
We can delete a component by assigning NULL to it.
> x[["age"]] <- NULL
> str(x)
List of 3
$ speaks : chr [1:2] "English" "French"
$ name : chr "Clair"
$ married: logi FALSE

> x$married <- NULL


> str(x)
List of 2
$ speaks: chr [1:2] "English" "French"
$ name : chr "Clair"
MATRIX
Matrix is a two dimensional data structure in R programming. Matrix is
similar to vector but additionally contains the dimension attribute. All attributes of
an object can be checked with the attributes() function (dimension can be checked
directly with the dim() function).
73

We can check if a variable is a matrix or not with the class() function.


>a
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9

> class(a)
[1] "matrix"

> attributes(a)
$dim
[1] 3 3

> dim(a)
[1] 3 3
Creating a matrix in R
Matrix can be created using the matrix() function. Dimension of the matrix can
be defined by passing appropriate value for arguments nrow and ncol. Providing
value for both dimension is not necessary. If one of the dimension is provided, the
other is inferred from length of the data.
> matrix(1:9, nrow = 3, ncol = 3)
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
> # same result is obtained by providing only one dimension

> matrix(1:9, nrow = 3)


[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
We can see that the matrix is filled column-wise. This can be reversed to row-
wise filling by passing TRUE to the argument byrow.
> matrix(1:9, nrow=3, byrow=TRUE) # fill matrix row-wise
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
74

In all cases, however, a matrix is stored in column-major order internally as


we will see in the subsequent sections. It is possible to name the rows and columns
of matrix during creation by passing a 2 element list to the argument dimnames.
> x <- matrix(1:9, nrow = 3, dimnames = list(c("X","Y","Z"), c("A","B","C")))
>x
ABC
X147
Y258
Z369
These names can be accessed or changed with two helpful functions
colnames() and rownames().
> colnames(x)
[1] "A" "B" "C"

> rownames(x)
[1] "X" "Y" "Z"

> # It is also possible to change names


> colnames(x) <- c("C1","C2","C3")
> rownames(x) <- c("R1","R2","R3")
>x
C1 C2 C3
R1 1 4 7
R2 2 5 8
R3 3 6 9
Another way of creating a matrix is by using functions cbind() and rbind() as in
column bind and row bind.
> cbind(c(1,2,3),c(4,5,6))
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6

> rbind(c(1,2,3),c(4,5,6))
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
75

Finally, you can also create a matrix from a vector by setting its dimension
using dim().
> x <- c(1,2,3,4,5,6)
>x
[1] 1 2 3 4 5 6
> class(x)
[1] "numeric"
> dim(x) <- c(2,3)
>x
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
> class(x)
[1] "matrix"
Accessing Elements of a matrix
We can access elements of a matrix using the square bracket [indexing]
method. Elements can be accessed as var[row, column]. Here rows and columns are
vectors.
Using integer vector as index
We specify the row numbers and column numbers as vectors and use it for
indexing. If any field inside the bracket is left blank, it selects all. We can use
negative integers to specify rows or columns to be excluded.
>x
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9

> x[c(1,2),c(2,3)] # select rows 1 & 2 and columns 2 & 3


[,1] [,2]
[1,] 4 7
[2,] 5 8

> x[c(3,2),] # leaving column field blank will select entire columns
[,1] [,2] [,3]
[1,] 3 6 9
[2,] 2 5 8
76

> x[,] # leaving row as well as column field blank will select entire matrix
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9

> x[-1,] # select all rows except first


[,1] [,2] [,3]
[1,] 2 5 8
[2,] 3 6 9
One thing to notice here is that, if the matrix returned after indexing is a row
matrix or column matrix, the result is given as a vector.
> x[1,]
[1] 1 4 7

> class(x[1,])
[1] "integer"
This behaviour can be avoided by using the argument drop = FALSE while
indexing.
> x[1,,drop=FALSE] # now the result is a 1X3 matrix rather than a vector
[,1] [,2] [,3]
[1,] 1 4 7

> class(x[1,,drop=FALSE])
[1] "matrix"
It is possible to index a matrix with a single vector. While indexing in such a
way, it acts like a vector formed by stacking columns of the matrix one after
another. The result is returned as a vector.
>x
[,1] [,2] [,3]
[1,] 4 8 3
[2,] 6 0 7
[3,] 1 2 9

> x[1:4]
[1] 4 6 1 8
> x[c(3,5,7)]
[1] 1 0 3
77

Using logical vector as index


Two logical vectors can be used to index a matrix. In such situation, rows and
columns where the value is TRUE is returned. These indexing vectors are recycled if
necessary and can be mixed with integer vectors.
>x
[,1] [,2] [,3]
[1,] 4 8 3
[2,] 6 0 7
[3,] 1 2 9

> x[c(TRUE,FALSE,TRUE),c(TRUE,TRUE,FALSE)]
[,1] [,2]
[1,] 4 8
[2,] 1 2
> x[c(TRUE,FALSE),c(2,3)] # the 2 element logical vector is recycled to 3
element vector
[,1] [,2]
[1,] 8 3
[2,] 2 9
It is also possible to index using a single logical vector where recycling takes
place if necessary.
> x[c(TRUE, FALSE)]
[1] 4 1 0 3 9
In the above example, the matrix x is treated as vector formed by stacking
columns of the matrix one after another, i.e., (4,6,1,8,0,2,3,7,9).
The indexing logical vector is also recycled and thus alternating elements are
selected. This property is utilized for filtering of matrix elements as shown below.
> x[x>5] # select elements greater than 5
[1] 6 8 7 9
> x[x%%2 == 0] # select even elements
[1] 4 6 8 0 2
Using character vector as index
Indexing with character vector is possible for matrix with named row or
column. This can be mixed with integer or logical indexing.
>x
ABC
78

[1,] 4 8 3
[2,] 6 0 7
[3,] 1 2 9

> x[,"A"]
[1] 4 6 1

> x[TRUE,c("A","C")]
AC
[1,] 4 3
[2,] 6 7
[3,] 1 9

> x[2:3,c("A","C")]
AC
[1,] 6 7
[2,] 1 9
Modifying a matrix in R
We can combine assignment operator with the above learned methods for
accessing elements of a matrix to modify it.
>x
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9

> x[2,2] <- 10; x # modify a single element


[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 10 8
[3,] 3 6 9
> x[x<5] <- 0; x # modify elements less than 5
[,1] [,2] [,3]
[1,] 0 0 7
[2,] 0 10 8
[3,] 0 6 9
79

A common operation with matrix is to transpose it. This can be done with the
function t().
> t(x) # transpose a matrix
[,1] [,2] [,3]
[1,] 0 0 0
[2,] 0 10 6
[3,] 7 8 9
We can add row or column using rbind() and cbind() function respectively.
Similarly, it can be removed through reassignment.
> cbind(x, c(1, 2, 3)) # add column
[,1] [,2] [,3] [,4]
[1,] 0 0 7 1
[2,] 0 10 8 2
[3,] 0 6 9 3

> rbind(x,c(1,2,3)) # add row


[,1] [,2] [,3]
[1,] 0 0 7
[2,] 0 10 8
[3,] 0 6 9
[4,] 1 2 3

> x <- x[1:2,]; x # remove last row


[,1] [,2] [,3]
[1,] 0 0 7
[2,] 0 10 8
Dimension of matrix can be modified as well, using the dim() function.
>x
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6

> dim(x) <- c(3,2); x # change to 3X2 matrix


[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
80

> dim(x) <- c(1,6); x # change to 1X6 matrix


[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 2 3 4 5 6
DATA FRAME
Data frame is a two dimensional data structure in R. It is a special case of a
list which has each component of equal length. Each component form the column
and contents of the component form the rows.
Check if a variable is a data frame or not
We can check if a variable is a data frame or not using the class() function.
>x
SN Age Name
1 1 21 John
2 2 15 Dora

> typeof(x) # data frame is a special case of list


[1] "list"

> class(x)
[1] "[Link]"
In this example, x can be considered as a list of 3 components with each
component having a two element vector. Some useful functions to know more about
a data frame are given below.
Functions of data frame
> names(x)
[1] "SN" "Age" "Name"
> ncol(x)
[1] 3
> nrow(x)
[1] 2
> length(x) # returns length of the list, same as ncol()
[1] 3
Creating a Data Frame in R
We can create a data frame using the [Link]() function. For example, the
above shown data frame can be created as follows.
> x <- [Link]("SN" = 1:2, "Age" = c(21,15), "Name" = c("John","Dora"))
> str(x) # structure of x
'[Link]': 2 obs of 3 variables:
$ SN : int 1 2
81

$ Age : num 21 15
$ Name: Factor w/ 2 levels "Dora","John": 2 1
Notice above that the third column, Name is of type factor, instead of a
character vector. By default, [Link]() function converts character vector into
factor.
To suppress this behavior, we can pass the argument
stringsAsFactors=FALSE.
> x <- [Link]("SN" = 1:2, "Age" = c(21,15), "Name" = c("John", "Dora"),
stringsAsFactors = FALSE)
> str(x) # now the third column is a character vector
'[Link]': 2 obs. of 3 variables:
$ SN : int 1 2
$ Age : num 21 15
$ Name: chr "John" "Dora"
Many data input functions of R like, [Link](), [Link](), [Link](),
[Link]() also read data into a data frame.
Accessing Components of a Data Frame
Components of data frame can be accessed like a list or like a matrix.
Accessing like a list
We can use either [, [[ or $ operator to access columns of data frame.
> x["Name"]
Name
1 John
2 Dora
> x$Name
[1] "John" "Dora"
> x[["Name"]]
[1] "John" "Dora"
> x[[3]]
[1] "John" "Dora"
Accessing with [[or $ is similar. However, it differs for [in that, indexing with]
will return us a data frame but the other two will reduce it into a vector.
Accessing like a matrix
Data frames can be accessed like a matrix by providing index for row and
column. To illustrate this, we use datasets already available in R. Datasets that are
available can be listed with the command library(help = "datasets").
We will use the trees dataset which contains Girth, Height and Volume for
Black Cherry Trees.
82

A data frame can be examined using functions like str() and head().
> str(trees)
'[Link]': 31 obs. of 3 variables:
$ Girth : num 8.3 8.6 8.8 10.5 10.7 10.8 11 11 11.1 11.2 ...
$ Height: num 70 65 63 72 81 83 66 75 80 75 ...
$ Volume: num 10.3 10.3 10.2 16.4 18.8 19.7 15.6 18.2 22.6 19.9 ...

> head(trees,n=3)
Girth Height Volume
1 8.3 70 10.3
2 8.6 65 10.3
3 8.8 63 10.2
We can see that trees is a data frame with 31 rows and 3 columns. We also
display the first 3 rows of the data frame.
Now we proceed to access the data frame like a matrix.
> trees[2:3,] # select 2nd and 3rd row
Girth Height Volume
2 8.6 65 10.3
3 8.8 63 10.2

> trees[trees$Height > 82,] # selects rows with Height greater than 82
Girth Height Volume
6 10.8 83 19.7
17 12.9 85 33.8
18 13.3 86 27.4
31 20.6 87 77.0
> trees[10:12,2]
[1] 75 79 76
We can see in the last case that the returned type is a vector since we
extracted data from a single column.
This behavior can be avoided by passing the argument drop=FALSE as follows.
> trees[10:12,2, drop = FALSE]
Height
10 75
11 79
12 76
83

Modifying a Data Frame in R


Data frames can be modified like we modified matrices through reassignment.
>x
SN Age Name
1 1 21 John
2 2 15 Dora

> x[1,"Age"] <- 20; x


SN Age Name
1 1 20 John
2 2 15 Dora
Adding Components
Rows can be added to a data frame using the rbind() function.
> rbind(x,list(1,16,"Paul"))
SN Age Name
1 1 20 John
2 2 15 Dora
3 1 16 Paul
Similarly, we can add columns using cbind().
> cbind(x,State=c("NY","FL"))
SN Age Name State
1 1 20 John NY
2 2 15 Dora FL
Since data frames are implemented as list, we can also add new columns
through simple list-like assignments.
>x
SN Age Name
1 1 20 John
2 2 15 Dora

> x$State <- c("NY","FL"); x


SN Age Name State
1 1 20 John NY
2 2 15 Dora FL
84

Deleting Component
Data frame columns can be deleted by assigning NULL to it.
> x$State <- NULL
>x
SN Age Name
1 1 20 John
2 2 15 Dora
Similarly, rows can be deleted through reassignments.
> x <- x[-1,]
>x
SN Age Name
2 2 15 Dora
FACTORS
Factor is a data structure used for fields that takes only predefined, finite
number of values (categorical data). For example: a data field such as marital
status may contain only values from single, married, separated, divorced, or
widowed.
In such case, we know the possible values beforehand and these predefined,
distinct values are called levels. Following is an example of factor in R.
>x
[1] single married married single
Levels: married single
Here, we can see that factor x has four elements and two levels. We can check
if a variable is a factor or not using class() function.
Similarly, levels of a factor can be checked using the levels() function.
> class(x)
[1] "factor"
> levels(x)
[1] "married" "single"
Creating a factor in R
We can create a factor using the function factor(). Levels of a factor are inferred
from the data if not provided.
> x <- factor(c("single", "married", "married", "single"));
>x
[1] single married married single
Levels: married single
> x <- factor(c("single", "married", "married", "single"), levels = c("single",
"married", "divorced"));
85

>x
[1] single married married single
Levels: single married divorced
We can see from the above example that levels may be predefined even if not
used. Factors are closely related with vectors. In fact, factors are stored as integer
vectors. This is clearly seen from its structure.
> x <- factor(c("single","married","married","single"))
> str(x)
Factor w/ 2 levels "married","single": 2 1 1 2
We see that levels are stored in a character vector and the individual elements
are actually stored as indices. Factors are also created when we read non-
numerical columns into a data frame. By default, [Link]() function converts
character vector into factor. To suppress this behavior, we have to pass the
argument stringsAsFactors = FALSE.
Accessing components of a factor
Accessing components of a factor is very much similar to that of vectors.
>x
[1] single married married single
Levels: married single

> x[3] # access 3rd element


[1] married
Levels: married single
> x[c(2, 4)] # access 2nd and 4th element
[1] married single
Levels: married single
> x[-1] # access all but 1st element
[1] married married single
Levels: married single
> x[c(TRUE, FALSE, FALSE, TRUE)] # using logical vector
[1] single single
Levels: married single
86

Modifying a factor
Components of a factor can be modified using simple assignments. However,
we cannot choose values outside of its predefined levels.
>x
[1] single married married single
Levels: single married divorced

> x[2] <- "divorced" # modify second element; x


[1] single divorced married single
Levels: single married divorced

> x[3] <- "widowed" # cannot assign values outside levels


Warning message:
In `[<-.factor`(`*tmp*`, 3, value = "widowed") :
invalid factor level, NA generated

>x
[1] single divorced <NA> single
Levels: single married divorced

A workaround to this is to add the value to the level first.

> levels(x) <- c(levels(x), "widowed") # add new level


> x[3] <- "widowed"
>x
[1] single divorced widowed single
Levels: single married divorced widowed

4.3.4 CLASSES AND OBJECTS


We can do object oriented programming in R. In fact, everything in R is an
object. An object is a data structure having some attributes and methods which act
on its attributes.
Class is a blueprint for the object. We can think of class like a sketch
(prototype) of a house. It contains all the details about the floors, doors, windows
etc. Based on these descriptions we build the house.
House is the object. As, many houses can be made from a description, we can
create many objects from a class. An object is also called an instance of a class and
the process of creating this object is called instantiation. While most programming
87

languages have a single class system, R has three class systems. Namely, S3, S4
and more recently Reference class systems.
They have their own features and peculiarities and choosing one over the other
is a matter of preference. Below, we give a brief introduction to them.
S3 Class
S3 class is somewhat primitive in nature. It lacks a formal definition and
object of this class can be created simply by adding a class attribute to it. This
simplicity accounts for the fact that it is widely used in R programming language.
In fact most of the R built-in classes are of this type.
Example 1: S3 class
> # create a list with required components
> s <- list(name = "John", age = 21, GPA = 3.5)
> # name the class appropriately
> class(s) <- "student"
Above example creates a S3 class with the given list.
S4 Class
S4 class are an improvement over the S3 class. They have a formally defined
structure which helps in making object of the same class look more or less similar.
Class components are properly defined using the setClass() function and objects are
created using the new() function.
Example 2: S4 class
< setClass("student", slots=list(name="character", age="numeric",
GPA="numeric"))
Reference Class
Reference class were introduced later, compared to the other two. It is more
similar to the object oriented programming we are used to seeing in other major
programming languages.
Reference classes are basically S4 classed with an environment added to it.
Example 3: Reference class
< setRefClass("student")

4.3.5 FLOW CONTROL STATEMENTS


Decision Making Statements
Decision making statements require the programmer to specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally,
other statements to be executed if the condition is determined to be false.
Following image 3.3 shows the general form of a typical decision-making
structure found in most of the programming languages
88

Figure 3.3 General form of decision-making statements

R provides the following three types of decision making statements.


 If statement
 If…else statement
 Switch statement
If Statement:
It consists of a Boolean expression followed by one or more statements
Syntax for creating an if statement in R is
if(boolean expression)
{
Statements / set of statements will execute if the boolean expression is true.
}
If the Boolean expression evaluates to be true, then the block of code inside
the if statement will be executed. If Boolean expression evaluates to be false, then
the first set of code after the end of the if statement (after the closing curly brace)
will be executed.
Example
x <- 30L
if([Link](x))
{
print("X is an Integer")
}
When the above code is compiled and executed, it produces the following
result.
[1] "X is an Integer"
89

If … Else Statement:
An if statement can be followed by an optional else statement which executes
when the boolean expression is false.
Syntax for creating an if...else statement in R is
if(boolean_expression)
{
Statements / set of statements will execute if the boolean expression is true.
} else
{
Statements / set of statements will execute if the boolean expression is false.
}
If the Boolean expression evaluates to be true, then the if block of code will be
executed, otherwise else block of code will be executed.
Example
x <- -5
if (x > 0)
{
print ("Non-negative number")
} else
{
print ("Negative number")
}
When the above code is compiled and executed, it produces the following
result.
[1] "Negative number"
Nested If … Else Statement:
The if…else ladder (if…else…if) statement allows you execute a block of code
among more than 2 alternatives
The syntax of if…else statement is:
if ( test_expression1)
{
statement1
} else if ( test_expression2)
{
statement2
} else if ( test_expression3)
{
statement3
} else
{
statement4
}
90

Only one statement will get executed depending upon the test_expressions.
Example
x <- 0
if (x < 0) {
print("Negative number")
} else if (x > 0) {
print("Positive number")
} else
print("Zero")
When the above code is compiled and executed, it produces the following result.
[1] "Zero"
Switch Statement:
switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is checked
for each case.
The basic syntax for creating a switch statement in R is
switch(expression, case1, case2, case3....)
Example:
x <- switch(
3,
"first",
"second",
"third",
"fourth"
)
print(x)
When the above code is compiled and executed, it produces the following
result −
[1] "third"

4.3.6 LOOPING AND LOOP CONTROL STATEMENTS


There may be a situation when you need to execute a block of code several
number of times. In general, statements are executed sequentially. The first
statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements
multiple times and the following image 3.4 shows the general form of a loop
statement in most of the programming languages
91

Figure 3.4 General form of looping statements


Following are the types of loop and loop control statements.
 For loop
 While loop
 Repeat loop
 Break and next
For loop:
A For loop is a repetition control structure that allows you to efficiently write a
loop that needs to execute a specific number of times.
The basic syntax for creating a for loop statement in R is
for (value in vector) {
statements
}
R’s for loops are particularly flexible in that they are not limited to integers, or
even numbers in the input. We can pass character vectors, logical vectors, lists or
expressions. The flow diagram of for loop is shown in figure 3.4.

Figure 3.5 General form of for loop


92

Example
v <- LETTERS[1:4]
for ( i in v) {
print(i)
}
When the above code is compiled and executed, it produces the following
result −
[1] "A"
[1] "B"
[1] "C"
[1] "D"
While Loop:
In R programming, while loops are used to loop until a specific condition is
met.
The basic syntax for creating a while loop statement in R is
while (test_expression)
{
statement
}
Here, test_expression is evaluated and the body of the loop is entered if the
result is TRUE. The statements inside the loop are executed and the flow returns to
evaluate the test_expression again. This is repeated each time until test_expression
evaluates to FALSE, in which case, the loop exits. The flow diagram of while loop is
shown in the figure 3.6.

Figure 3.6 Flow diagram of while loop


93

Example
i <- 1
while (i < 6) {
print(i)
i = i+1
}
Output
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
In the above example, i is initially initialized to 1. Here, the test_expression is i
< 6 which evaluates to TRUE since 1 is less than 6. So, the body of the loop is
entered and i is printed and incremented. Incrementing i is important as this will
eventually meet the exit condition. Failing to do so will result into an infinite loop.
In the next iteration, the value of i is 2 and the loop continues. This will
continue until i takes the value 6. The condition 6 < 6 will give FALSE and the while
loop finally exits.
Repeat Loop:
A repeat loop is used to iterate over a block of code multiple number of times.
There is no condition check in repeat loop to exit the loop. We must ourselves put a
condition explicitly inside the body of the loop and use the break statement to exit
the loop. Failing to do so will result into an infinite loop.
The basic syntax for creating a repeat loop statement in R is
repeat {
statement
}
In the statement block, we must use the break statement to exit the loop. The
flow diagram for repeat loop is shown in the figure 3.7.
94

Figure 3.7 Flow diagram of repeat loop

Example
x <- 1
repeat {
print(x)
x = x+1
if (x == 6){
break
}
}
Output
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
In the above example, we have used a condition to check and exit the loop
when x takes the value of 6. Hence, we see in our output that only values from 1 to
5 get printed.
break and next Statement:
In R programming, a normal looping sequence can be altered using the break
or the next statement.
break statement
A break statement is used inside a loop (repeat, for, while) to stop the
iterations and flow the control outside of the loop. In a nested looping situation,
where there is a loop inside another loop, this statement exits from the innermost
loop that is being evaluated.
95

The basic syntax of break statement is:


if (test_expression) {
break
}
The break statement can also be used inside the else branch of if...else
statement. The flow diagram of break statement is shown in the figure 3.8.

Figure 3.8 Flow diagram of break statement


Example
x <- 1:5
for (val in x) {
if (val == 3){
break
}
print(val)
}
Output
[1] 1
[1] 2
In this example, we iterate over the vector x, which has consecutive numbers
from 1 to 5. Inside the for loop we have used a if condition to break if the current
value is equal to 3. As we can see from the output, the loop terminates when it
encounters the break statement.
next statement:
A next statement is useful when we want to skip the current iteration of a loop
without terminating it. On encountering next, the R parser skips further evaluation
and starts next iteration of the loop.
96

The syntax of next statement is:


if (test_condition) {
next
}
The next statement can also be used inside the else branch of if...else
statement. The flow diagram of next statement is shown in the figure 3.9.

Figure 3.9 Flow diagram of next statement


Example
x <- 1:5
for (val in x) {
if (val == 3) {
next
}
print(val)
}
Output
[1] 1
[1] 2
[1] 4
[1] 5
In the above example, we use the next statement inside a condition to check if
the value is equal to 3. If the value is equal to 3, the current evaluation stops (value
is not printed) but the loop continues with the next iteration. The output reflects
this situation.
4.3.7 R FUNCTIONS
Functions are used to logically break our code into simpler parts which
become easy to maintain and understand. It’s pretty straightforward to create your
own function in R programming.
97

Syntax for Writing Functions in R


func_name <- function (argument) {
statement
}
Here, we can see that the reserved word function is used to declare a function
in R. The statements within the curly braces form the body of the function. These
braces are optional if the body contains only a single expression. Finally, this
function object is given a name by assigning it to a variable, func_name.
Example
pow <- function(x, y) {
# function to print x raised to the power y
result <- x^y
print(paste(x,"raised to the power", y, "is", result))
}
Here, we created a function called pow(). It takes two arguments, finds the first
argument raised to the power of second argument and prints the result in
appropriate format. We have used a built-in function paste() which is used to
concatenate strings.
Calling a function
We can call the above function as follows.
>pow(8, 2)
[1] "8 raised to the power 2 is 64"

> pow(2, 8)
[1] "2 raised to the power 8 is 256"
Here, the arguments used in the function declaration (x and y) are called
formal arguments and those used while calling the function are called actual
arguments.
Named Arguments
In the above function calls, the argument matching of formal argument to the
actual arguments takes place in positional order. This means that, in the call
pow(8,2), the formal arguments x and y are assigned 8 and 2 respectively.
We can also call the function using named arguments. When calling a function
in this way, the order of the actual arguments doesn’t matter. For example, all of
the function calls given below are equivalent.
> pow(8, 2)
[1] "8 raised to the power 2 is 64"

> pow(x = 8, y = 2)
[1] "8 raised to the power 2 is 64"
98

> pow(y = 2, x = 8)
[1] "8 raised to the power 2 is 64"
Furthermore, we can use named and unnamed arguments in a single call. In
such case, all the named arguments are matched first and then the remaining
unnamed arguments are matched in a positional order.
> pow(x=8, 2)
[1] "8 raised to the power 2 is 64"

> pow(2, x=8)


[1] "8 raised to the power 2 is 64"
In all the examples above, x gets the value 8 and y gets the value 2.
Default Values for Arguments
We can assign default values to arguments in a function in R. This is done by
providing an appropriate value to the formal argument in the function declaration.
Here is the above function with a default value for y.
pow <- function(x, y = 2) {
# function to print x raised to the power y
result <- x^y
print(paste(x,"raised to the power", y, "is", result))
}
The use of default value to an argument makes it optional when calling the
function.
> pow(3)
[1] "3 raised to the power 2 is 9"

> pow(3,1)
[1] "3 raised to the power 1 is 3"
Here, y is optional and will take the value 2 when not provided.
Functions returning a value
Many a times, we will require our functions to do some processing and return
back the result. This is accomplished with the return() function in R.
Syntax of return()
return(expression)
The value returned from a function can be any valid object.
99

Example
Let us look at an example which will return whether a given number is
positive, negative or zero.
check <- function(x) {
if (x > 0) {
result <- "Positive"
}
else if (x < 0) {
result <- "Negative"
}
else {
result <- "Zero"
}
return(result)
}
Here, are some sample runs.
> check(1)
[1] "Positive"

> check(-10)
[1] "Negative"

> check(0)
[1] "Zero"
Functions without return()
If there are no explicit returns from a function, the value of the last evaluated
expression is returned automatically in R. For example, the following is equivalent
to the above function.
check <- function(x) {
if (x > 0) {
result <- "Positive"
}
else if (x < 0) {
result <- "Negative"
}
else {
result <- "Zero"
}
100

result
}
We generally use explicit return() functions to return a value immediately from
a function.
If it is not the last statement of the function, it will prematurely end the
function bringing the control to the place from which it was called.
check <- function(x) {
if (x>0) {
return("Positive")
}
else if (x<0) {
return("Negative")
}
else {
return("Zero")
}
}
In the above example, if x > 0, the function immediately returns "Positive"
without evaluating rest of the body.
Multiple Returns
The return() function can return only a single object. If we want to return
multiple values in R, we can use a list (or other objects) and return it.
Following is an example.
multi_return <- function() {
my_list <- list("color" = "red", "size" = 20, "shape" = "round")
return(my_list)
}
Here, we create a list my_list with multiple elements and return this single list.
> a <- multi_return()
> a$color
[1] "red"
> a$size
[1] 20
> a$shape
[1] "round
101

4.4 REVISION POINTS


What is R? : R is a programming language and environment commonly used in
statistical computing, data analytics and scientific research. It is one of the most
popular languages used by statisticians, data analysts, researchers and marketers
to retrieve, clean, analyze, visualize and present data. Due to its expressive syntax
and easy-to-use interface, it has grown in popularity in recent years.
Vector : Vector is a basic data structure in R. It contains element of the same
type. The data types can be logical, integer, double, character, complex or raw.
Lists : List is a data structure having components of mixed data types. A
vector having all elements of the same type is called atomic vector but a vector
having elements of different type is called list.
Matrix : Matrix is a two dimensional data structure in R programming. Matrix
is similar to vector but additionally contains the dimension attribute.
Data frame : Data frame is a two dimensional data structure in R. It is a
special case of a list which has each component of equal length. Each component
form the column and contents of the component form the rows.
Factors : Factor is a data structure used for fields that takes only predefined,
finite number of values (categorical data).
4.5 INTEXT QUESTIONS
1. What is R?
2. What are some advantages of R?
3. What are some disadvantages of R?
4. How do you assign a variable in R?
5. What are the different data types / objects in R?
6. How do you import data in R?
7. What is factor and give the uses of it?
8. How do you concatenate strings in R?
9. Why R is useful for data science?
10. Explain which() function in R.
4.6 SUMMARY
In this unit we have discussed the concept of R Programming with its syntax,
operators, data types, objects, functions, flow control statements and loop control
statements.
4.7 TERMINAL EXERCISES
1. What are the differences between [Link]() and [Link]()? When do you
use these two functions?
2. R suffers from the disadvantage of being restricted to the local memory.
Could you elaborate the precise memory limit in R?
3. Suppose that I want to know the values in c(1, 2, 6, 3, 19) that are not
present in c(2, 6, 14, 3, 15). How can you carry this out using built-in
function as well as without it?
102

4.8 SUPPLEMENTARY MATERIALS


1. Getting Started with RStudio, John Verzani, O'Reilly Media
2. R Programming for Beginners, Steven keller, Create Space Independent
Publishing Platform
4.9 ASSIGNMENTS
1. Write a R program to create a vector which contains 10 random integer
values between -50 and +50
2. Write a R program to create a list of random numbers in normal distribution
and count occurrences of each value.
4.10 SUGGESTED READINGS / E-REFERENCES
1. [Link]
2. [Link]
3. [Link]
4.11 LEARNING ACTIVITIES
1. Write a R program to find Sum, Mean and Product of a Vector, ignore
element like NA or NaN
4.12 KEYWORDS
Vector, Lists, Matrix, Data frame, Factor

103

UNIT- V
STATISTICAL MODELS, GRAPHICAL PROCEDURES, PACKAGES
5.1 INTRODUCTION
This chapter discusses the concept of Statistical models, Graphical procedures
and Packages. Also we will be discussing implementation of above concepts using R
programming,
5.2 OBJECTIVES
The objective of this Unit is to make the student learns the basic concepts and
its implementation of Statistical models, Graphical procedures and Packages using
R Programming.
5.3 CONTENTS
5.3.1 STATISTICAL MODELS IN R
This section presumes the reader has some familiarity with statistical
methodology, in particular with regression analysis and the analysis of variance.
Later we make some rather more ambitious presumptions, namely that something
is known about generalized linear models and nonlinear regression.
The requirements for fitting statistical models are sufficiently well defined to
make it possible to construct general tools that apply in a broad spectrum of
problems.
R provides an interlocking suite of facilities that make fitting statistical models
very simple. As we mention in the introduction, the basic output is minimal, and
one needs to ask for the details by calling extractor functions.
Defining statistical models; formulae
The template for a statistical model is a linear regression model with
independent, homoscedastic errors
y_i = sum_{j=0}^p beta_j x_{ij} + e_i, i = 1, …, n,
where the e_i are NID(0, sigma^2). In matrix terms this would be written
y = X beta + e
where the y is the response vector, X is the model matrix or design matrix and
has columns x_0, x_1, …, x_p, the determining variables. Very often x_0 will be a
column of ones defining an intercept term.
Example
Before giving a formal specification, a few examples may usefully set the
picture.
Suppose y, x, x0, x1, x2, … are numeric variables, X is a matrix and A, B, C,
… are factors. The following formulae on the left side below specify statistical
models as described on the right.
y~x
y~1+x
104

Both imply the same simple linear regression model of y on x. The first has an
implicit intercept term, and the second an explicit one.
y~0+x
y ~ -1 + x
y~x–1
Simple linear regression of y on x through the origin (that is, without an
intercept term).
log(y) ~ x1 + x2
Multiple regression of the transformed variable, log(y), on x1 and x2 (with an
implicit intercept term).
y ~ poly(x,2)
y ~ 1 + x + I(x^2)
Polynomial regression of y on x of degree 2. The first form uses orthogonal
polynomials, and the second uses explicit powers, as basis.
y ~ X + poly(x,2)
Multiple regression y with model matrix consisting of the matrix X as well as
polynomial terms in x to degree 2.
y~A
Single classification analysis of variance model of y, with classes determined
by A.
y~A+x
Single classification analysis of covariance model of y, with classes determined
by A, and with covariate x.
y ~ A*B
y ~ A + B + A:B
y ~ B %in% A
y ~ A/B
Two factor non-additive model of y on A and B. The first two specify the same
crossed classification and the second two specify the same nested classification. In
abstract terms all four specify the same model subspace.
y ~ (A + B + C)^2
y ~ A*B*C - A:B:C
Three factor experiment but with a model containing main effects and two
factor interactions only. Both formulae specify the same model.
y~A*x
y ~ A/x
y ~ A/(1 + x) – 1
105

Separate simple linear regression models of y on x within the levels of A, with


different codings. The last form produces explicit estimates of as many different
intercepts and slopes as there are levels in A.
y ~ A*B + Error(C)
An experiment with two treatment factors, A and B, and error strata
determined by factor C. For example a split plot experiment, with whole plots (and
hence also subplots), determined by factor C.
The operator ~ is used to define a model formula in R. The form, for an
ordinary linear model, is
response ~ op_1 term_1 op_2 term_2 op_3 term_3 …
where
response
is a vector or matrix, (or expression evaluating to a vector or matrix) defining
the response variable(s).
op_i
is an operator, either + or -, implying the inclusion or exclusion of a term in
the model, (the first is optional).
term_i
is either a vector or matrix expression, or 1, a factor, or a formula expression
consisting of factors, vectors or matrices connected by formula operators.
In all cases each term defines a collection of columns either to be added to or
removed from the model matrix. A 1 stands for an intercept column and is by
default included in the model matrix unless explicitly removed.
The formula operators are similar in effect to the Wilkinson and Rogers
notation used by such programs as Glim and Genstat. One inevitable change is
that the operator ‘.’ becomes ‘:’ since the period is a valid name character in R.
The notation is summarized below (based on Chambers & Hastie, 1992, p.29):
Y~M
Y is modeled as M.

M_1 + M_2
Include M_1 and M_2.

M_1 - M_2
Include M_1 leaving out terms of M_2.
M_1 : M_2
The tensor product of M_1 and M_2. If both terms are factors, then the
“subclasses” factor.
106

M_1 %in% M_2


Similar to M_1:M_2, but with a different coding.

M_1 * M_2
M_1 + M_2 + M_1:M_2.

M_1 / M_2
M_1 + M_2 %in% M_1.

M^n
All terms in M together with “interactions” up to order n

I(M)
Insulate M. Inside M all operators have their normal arithmetic meaning, and
that term appears in the model matrix.
Note that inside the parentheses that usually enclose function arguments all
operators have their normal arithmetic meaning. The function I() is an identity
function used to allow terms in model formulae to be defined using arithmetic
operators.
Note particularly that the model formulae specify the columns of the model
matrix, the specification of the parameters being implicit. This is not the case in
other contexts, for example in specifying nonlinear models.
Linear models
The basic function for fitting ordinary multiple models is lm(), and a streamlined
version of the call is as follows:
> [Link] <- lm(formula, data = [Link])
For example
> fm2 <- lm(y ~ x1 + x2, data = production)
would fit a multiple regression model of y on x1 and x2 (with implicit intercept
term).
The important (but technically optional) parameter data = production specifies
that any variables needed to construct the model should come first from the
production data frame. This is the case regardless of whether data frame
production has been attached on the search path or not.
Generic functions for extracting model information
The value of lm() is a fitted model object; technically a list of results of class
"lm". Information about the fitted model can then be displayed, extracted, plotted
107

and so on by using generic functions that orient themselves to objects of class "lm".
These include
add1 deviance formula predict step
alias drop1 kappa print summary
anova effects labels proj vcov
coef family plot residuals
A brief description of the most commonly used ones is given below.
anova(object_1, object_2)
Compare a submodel with an outer model and produce an analysis of
variance table.
coef(object)
Extract the regression coefficient (matrix).
Long form: coefficients(object).

deviance(object)
Residual sum of squares, weighted if appropriate.

formula(object)
Extract the model formula.

plot(object)
Produce four plots, showing residuals, fitted values and some
diagnostics.

predict(object, newdata=[Link])
The data frame supplied must have variables specified with the same labels as
the original. The value is a vector or matrix of predicted values corresponding to the
determining variable values in [Link].
print(object)
Print a concise version of the object. Most often used implicitly.

residuals(object)
Extract the (matrix of) residuals, weighted as appropriate.
Short form: resid(object).

step(object)
108

Select a suitable model by adding or dropping terms and preserving


hierarchies. The model with the smallest value of AIC (Akaike’s An Information
Criterion) discovered in the stepwise search is returned.
summary(object)
Print a comprehensive summary of the results of the regression
analysis.

vcov(object)
Returns the variance-covariance matrix of the main parameters of a
fitted model object.
Analysis of variance and model comparison
The model fitting function aov(formula, data=[Link]) operates at the
simplest level in a very similar way to the function lm(), and most of the generic
functions listed in the table in Generic functions for extracting model information
apply.
It should be noted that in addition aov() allows an analysis of models with
multiple error strata such as split plot experiments, or balanced incomplete block
designs with recovery of inter-block information. The model formula
response ~ [Link] + Error([Link])
specifies a multi-stratum experiment with error strata defined by the
[Link]. In the simplest case, [Link] is simply a factor, when it
defines a two strata experiment, namely between and within the levels of the factor.
For example, with all determining variables factors, a model formula such as
that in:
> fm <- aov(yield ~ v + n*p*k + Error(farms/blocks), data=[Link])
would typically be used to describe an experiment with mean model v + n*p*k
and three error strata, namely “between farms”, “within farms, between blocks” and
“within blocks”.
ANOVA tables
Note also that the analysis of variance table (or tables) are for a sequence of
fitted models. The sums of squares shown are the decrease in the residual sums of
squares resulting from an inclusion of that term in the model at that place in the
sequence. Hence only for orthogonal experiments will the order of inclusion be
inconsequential.
For multistratum experiments the procedure is first to project the response
onto the error strata, again in sequence, and to fit the mean model to each
projection. For further details, see Chambers & Hastie (1992).
109

A more flexible alternative to the default full ANOVA table is to compare two or
more models directly using the anova() function.
> anova([Link].1, [Link].2, …)
The display is then an ANOVA table showing the differences between the fitted
models when fitted in sequence. The fitted models being compared would usually be
an hierarchical sequence, of course. This does not give different information to the
default, but rather makes it easier to comprehend and control.
Updating fitted models
The update() function is largely a convenience function that allows a model to
be fitted that differs from one previously fitted usually by just a few additional or
removed terms. Its form is
> [Link] <- update([Link], [Link])
In the [Link] the special name consisting of a period, ‘.’, only, can be
used to stand for “the corresponding part of the old model formula”. For example,
> fm05 <- lm(y ~ x1 + x2 + x3 + x4 + x5, data = production)
> fm6 <- update(fm05, . ~ . + x6)
> smf6 <- update(fm6, sqrt(.) ~ .)
would fit a five variate multiple regression with variables (presumably) from
the data frame production, fit an additional model including a sixth regressor
variable, and fit a variant on the model where the response had a square root
transform applied.
Note especially that if the data= argument is specified on the original call to
the model fitting function, this information is passed on through the fitted model
object to update() and its allies. The name ‘.’ can also be used in other contexts, but
with slightly different meaning. For example
> fmfull <- lm(y ~ . , data = production)
would fit a model with response y and regressor variables all other variables in
the data frame production. Other functions for exploring incremental sequences of
models are add1(), drop1() and step(). The names of these give a good clue to their
purpose, but for full details see the on-line help.
Generalized linear models
Generalized linear modeling is a development of linear models to accommodate
both non-normal response distributions and transformations to linearity in a clean
and straightforward way.
A generalized linear model may be described in terms of the following sequence
of assumptions:
There is a response, y, of interest and stimulus variables x_1, x_2, …, whose
values influence the distribution of the response.
110

The stimulus variables influence the distribution of y through a single linear


function, only. This linear function is called the linear predictor, and is usually
written
eta = beta_1 x_1 + beta_2 x_2 + … + beta_p x_p,
hence x_i has no influence on the distribution of y if and only if beta_i is zero.
The distribution of y is of the form
f_Y(y; mu, phi)
= exp((A/phi) * (y lambda(mu) - gamma(lambda(mu))) + tau(y, phi))
where phi is a scale parameter (possibly known), and is constant for all
observations, A represents a prior weight, assumed known but possibly varying
with the observations, and $\mu$ is the mean of y. So it is assumed that the
distribution of y is determined by its mean and possibly a scale parameter as well.
The mean, mu, is a smooth invertible function of the linear predictor:
mu = m(eta), eta = m^{-1}(mu) = ell(mu)
and this inverse function, ell(), is called the link function.
These assumptions are loose enough to encompass a wide class of models
useful in statistical practice, but tight enough to allow the development of a unified
methodology of estimation and inference, at least approximately. The reader is
referred to any of the current reference works on the subject for full details, such as
McCullagh & Nelder (1989) or Dobson (1990).
Families
The class of generalized linear models handled by facilities supplied in R
includes gaussian, binomial, poisson, inverse gaussian and gamma response
distributions and also quasi-likelihood models where the response distribution is
not explicitly specified. In the latter case the variance function must be specified as
a function of the mean, but in other cases this function is implied by the response
distribution.
Each response distribution admits a variety of link functions to connect the
mean with the linear predictor. Those automatically available are shown in the
following table:
Family name Link functions
binomial logit, probit, log, cloglog
gaussian identity, log, inverse
Gamma identity, inverse, log
[Link] 1/mu^2, identity, inverse, log
poisson identity, log, sqrt
quasi logit, probit, cloglog, identity, inverse, log,
1/mu^2, sqrt
111

The combination of a response distribution, a link function and various other


pieces of information that are needed to carry out the modeling exercise is called
the family of the generalized linear model.
The glm() function
Since the distribution of the response depends on the stimulus variables
through a single linear function only, the same mechanism as was used for linear
models can still be used to specify the linear part of a generalized model. The family
has to be specified in a different way.
The R function to fit a generalized linear model is glm() which uses the form
> [Link] <- glm(formula, family=[Link], data=[Link])
The only new feature is the [Link], which is the instrument by which
the family is described. It is the name of a function that generates a list of functions
and expressions that together define and control the model and estimation process.
Although this may seem a little complicated at first sight, its use is quite simple.
The names of the standard, supplied family generators are given under “Family
Name” in the table in Families. Where there is a choice of links, the name of the
link may also be supplied with the family name, in parentheses as a parameter. In
the case of the quasi family, the variance function may also be specified in this way.
Some examples make the process clear.
The gaussian family
A call such as
> fm <- glm(y ~ x1 + x2, family = gaussian, data = sales)
achieves the same result as
> fm <- lm(y ~ x1+x2, data=sales)
but much less efficiently. Note how the gaussian family is not automatically
provided with a choice of links, so no parameter is allowed. If a problem requires a
gaussian family with a nonstandard link, this can usually be achieved through the
quasi family, as we shall see later.
The binomial family
Consider a small, artificial example, from Silvey (1970).
On the Aegean island of Kalythos the male inhabitants suffer from a congenital
eye disease, the effects of which become more marked with increasing age. Samples
of islander males of various ages were tested for blindness and the results recorded.
The data is shown below:
Age: 20 35 45 55 70
No. tested: 50 50 50 50 50
No. blind: 6 17 26 37 44
The problem we consider is to fit both logistic and probit models to this data,
and to estimate for each model the LD50, that is the age at which the chance of
blindness for a male inhabitant is 50%.
112

If y is the number of blind at age x and n the number tested, both models have
the form y ~ B(n, F(beta_0 + beta_1 x)) where for the probit case, F(z) = Phi(z) is the
standard normal distribution function, and in the logit case (the default), F(z) =
e^z/(1+e^z). In both cases the LD50 is LD50 = - beta_0/beta_1 that is, the point at
which the argument of the distribution function is zero.
The first step is to set the data up as a data frame
> kalythos <- [Link](x = c(20,35,45,55,70), n = rep(50,5),
y = c(6,17,26,37,44))
To fit a binomial model using glm() there are three possibilities for the response:
 If the response is a vector it is assumed to hold binary data, and so must be
a 0/1 vector.
 If the response is a two-column matrix it is assumed that the first column
holds the number of successes for the trial and the second holds the
number of failures.
 If the response is a factor, its first level is taken as failure (0) and all other
levels as ‘success’ (1).
Here we need the second of these conventions, so we add a matrix to our data
frame:
> kalythos$Ymat <- cbind(kalythos$y, kalythos$n - kalythos$y)
To fit the models we use
> fmp <- glm(Ymat ~ x, family = binomial(link=probit), data = kalythos)
> fml <- glm(Ymat ~ x, family = binomial, data = kalythos)
Since the logit link is the default the parameter may be omitted on the second
call. To see the results of each fit we could use
> summary(fmp)
> summary(fml)
Both models fit (all too) well. To find the LD50 estimate we can use a simple
function:
> ld50 <- function(b) -b[1]/b[2]
> ldp <- ld50(coef(fmp)); ldl <- ld50(coef(fml)); c(ldp, ldl)
The actual estimates from this data are 43.663 years and 43.601 years
respectively.
Poisson models
With the Poisson family the default link is the log, and in practice the major
use of this family is to fit surrogate Poisson log-linear models to frequency data,
whose actual distribution is often multinomial. This is a large and important
subject we will not discuss further here. It even forms a major part of the use of
non-gaussian generalized models overall.
113

Occasionally genuinely Poisson data arises in practice and in the past it was
often analyzed as gaussian data after either a log or a square-root transformation.
As a graceful alternative to the latter, a Poisson generalized linear model may
be fitted as in the following example:
> fmod <- glm(y ~ A + B + x, family = poisson(link=sqrt),
data = [Link])
Quasi-likelihood models
For all families the variance of the response will depend on the mean and will
have the scale parameter as a multiplier. The form of dependence of the variance on
the mean is a characteristic of the response distribution; for example for the
poisson distribution Var(y) = mu.
For quasi-likelihood estimation and inference the precise response distribution
is not specified, but rather only a link function and the form of the variance
function as it depends on the mean. Since quasi-likelihood estimation uses formally
identical techniques to those for the gaussian distribution, this family provides a
way of fitting gaussian models with non-standard link functions or variance
functions, incidentally.
For example, consider fitting the non-linear regression y = theta_1 z_1 / (z_2 -
theta_2) + e which may be written alternatively as y = 1 / (beta_1 x_1 + beta_2 x_2)
+ e where x_1 = z_2/z_1, x_2 = -1/z_1, beta_1 = 1/theta_1, and beta_2 =
theta_2/theta_1. Supposing a suitable data frame to be set up we could fit this
non-linear regression as
> nlfit <- glm(y ~ x1 + x2 - 1, family = quasi(link=inverse, variance=constant),
data = biochem)
The reader is referred to the manual and the help document for further
information, as needed.
Nonlinear least squares and maximum likelihood models
Certain forms of nonlinear model can be fitted by Generalized Linear Models
(glm()). But in the majority of cases we have to approach the nonlinear curve fitting
problem as one of nonlinear optimization. R’s nonlinear optimization routines are
optim(), nlm() and nlminb(), which provide the functionality (and more) of S-PLUS’s
ms() and nlminb(). We seek the parameter values that minimize some index of lack-
of-fit, and they do this by trying out various parameter values iteratively. Unlike
linear regression for example, there is no guarantee that the procedure will
converge on satisfactory estimates. All the methods require initial guesses about
what parameter values to try, and convergence may depend critically upon the
quality of the starting values.
Least squares
One way to fit a nonlinear model is by minimizing the sum of the squared
errors (SSE) or residuals. This method makes sense if the observed errors could
have plausibly arisen from a normal distribution.
114

Here is an example from Bates & Watts (1988), page 51. The data are:
> x <- c(0.02, 0.02, 0.06, 0.06, 0.11, 0.11, 0.22, 0.22, 0.56, 0.56,
1.10, 1.10)
> y <- c(76, 47, 97, 107, 123, 139, 159, 152, 191, 201, 207, 200)
The fit criterion to be minimized is:
> fn <- function(p) sum((y - (p[1] * x)/(p[2] + x))^2)
In order to do the fit we need initial estimates of the parameters. One way to
find sensible starting values is to plot the data, guess some parameter values, and
superimpose the model curve using those values.
> plot(x, y)
> xfit <- seq(.02, 1.1, .05)
> yfit <- 200 * xfit/(0.1 + xfit)
> lines(spline(xfit, yfit))
We could do better, but these starting values of 200 and 0.1 seem adequate.
Now do the fit:
> out <- nlm(fn, p = c(200, 0.1), hessian = TRUE)
After the fitting, out$minimum is the SSE, and out$estimate are the least
squares estimates of the parameters.
To obtain the approximate standard errors (SE) of the estimates we do:
> sqrt(diag(2*out$minimum/(length(y) - 2) * solve(out$hessian)))
The 2 which is subtracted in the line above represents the number of
parameters. A 95% confidence interval would be the parameter estimate +/- 1.96
SE.
We can superimpose the least squares fit on a new plot:
> plot(x, y)
> xfit <- seq(.02, 1.1, .05)
> yfit <- 212.68384222 * xfit/(0.06412146 + xfit)
> lines(spline(xfit, yfit))
The standard package stats provides much more extensive facilities for fitting
non-linear models by least squares. The model we have just fitted is the Michaelis-
Menten model, so we can use
> df <- [Link](x=x, y=y)
> fit <- nls(y ~ SSmicmen(x, Vm, K), df)
> fit
Nonlinear regression model
model: y ~ SSmicmen(x, Vm, K)
115

data: df
Vm K
212.68370711 0.06412123
residual sum-of-squares: 1195.449
> summary(fit)

Formula: y ~ SSmicmen(x, Vm, K)


Parameters:
Estimate Std. Error t value Pr(>|t|)
Vm 2.127e+02 6.947e+00 30.615 3.24e-11
K 6.412e-02 8.281e-03 7.743 1.57e-05
Residual standard error: 10.93 on 10 degrees of freedom
Correlation of Parameter Estimates:
Vm
K 0.7651
Maximum likelihood
Maximum likelihood is a method of nonlinear model fitting that applies even if
the errors are not normal. The method finds the parameter values which maximize
the log likelihood, or equivalently which minimize the negative log-likelihood. Here
is an example from Dobson (1990), pp. 108–111. This example fits a logistic model
to dose-response data, which clearly could also be fit by glm(). The data are:
> x <- c(1.6907, 1.7242, 1.7552, 1.7842, 1.8113,
1.8369, 1.8610, 1.8839)
> y <- c( 6, 13, 18, 28, 52, 53, 61, 60)
> n <- c(59, 60, 62, 56, 63, 59, 62, 60)
The negative log-likelihood to minimize is:
> fn <- function(p)
sum( - (y*(p[1]+p[2]*x) - n*log(1+exp(p[1]+p[2]*x))
+ log(choose(n, y)) ))
We pick sensible starting values and do the fit:
> out <- nlm(fn, p = c(-50,20), hessian = TRUE)
After the fitting, out$minimum is the negative log-likelihood, and out$estimate
are the maximum likelihood estimates of the parameters.
To obtain the approximate SEs of the estimates we do:
> sqrt(diag(solve(out$hessian)))
A 95% confidence interval would be the parameter estimate +/- 1.96 SE.
116

5.3.2 GRAPHICAL PROCEDURES


Graphical facilities are an important and extremely versatile component of the
R environment. It is possible to use the facilities to display a wide variety of
statistical graphs and also to build entirely new types of graph.
The graphics facilities can be used in both interactive and batch modes, but in
most cases, interactive use is more productive. Interactive use is also easy because
at startup time R initiates a graphics device driver which opens a special graphics
window for the display of interactive graphics. Although this is done automatically,
it may useful to know that the command used is X11() under UNIX, windows()
under Windows and quartz() under macOS. A new device can always be opened by
[Link]().
Once the device driver is running, R plotting commands can be used to
produce a variety of graphical displays and to create entirely new kinds of display.
Plotting commands are divided into three basic groups:
 High-level plotting functions create a new plot on the graphics device,
possibly with axes, labels, titles and so on.
 Low-level plotting functions add more information to an existing plot, such
as extra points, lines and labels.
 Interactive graphics functions allow you interactively add information to, or
extract information from, an existing plot, using a pointing device such as a
mouse.
In addition, R maintains a list of graphical parameters which can be
manipulated to customize your plots.
This manual only describes what are known as ‘base’ graphics. A separate
graphics sub-system in package grid coexists with base – it is more powerful but
harder to use. There is a recommended package lattice which builds on grid and
provides ways to produce multi-panel plots akin to those in the Trellis system in S.
 High-level plotting commands
 Low-level plotting commands
 Graphics parameters
 Dynamic graphics
High-level plotting commands
High-level plotting functions are designed to generate a complete plot of the
data passed as arguments to the function. Where appropriate, axes, labels and
titles are automatically generated (unless you request otherwise.) High-level plotting
commands always start a new plot, erasing the current plot if necessary.
 The plot() function
 Displaying multivariate data
 Display graphics
 Arguments to high-level plotting functions
117

The plot() function


One of the most frequently used plotting functions in R is the plot() function.
This is a generic function: the type of plot produced is dependent on the type or
class of the first argument.
plot(x, y)
plot(xy)
If x and y are vectors, plot(x, y) produces a scatterplot of y against x. The same
effect can be produced by supplying one argument (second form) as either a list
containing two elements x and y or a two-column matrix.
plot(x)
If x is a time series, this produces a time-series plot. If x is a numeric vector, it
produces a plot of the values in the vector against their index in the vector. If x is a
complex vector, it produces a plot of imaginary versus real parts of the vector
elements.
plot(f)
plot(f, y)
f is a factor object, y is a numeric vector. The first form generates a bar plot of
f; the second form produces boxplots of y for each level of f.
plot(df)
plot(~ expr)
plot(y ~ expr)
df is a data frame, y is any object, expr is a list of object names separated by
‘+’ (e.g., a + b + c). The first two forms produce distributional plots of the variables
in a data frame (first form) or of a number of named objects (second form). The
third form plots y against every object named in expr.
Displaying multivariate data
R provides two very useful functions for representing multivariate data. If X is
a numeric matrix or data frame, the command
> pairs(X)
produces a pairwise scatterplot matrix of the variables defined by the columns
of X, that is, every column of X is plotted against every other column of X and the
resulting n(n-1) plots are arranged in a matrix with plot scales constant over the
rows and columns of the matrix.
When three or four variables are involved a coplot may be more enlightening. If
a and b are numeric vectors and c is a numeric vector or factor object (all of the
same length), then the command
> coplot(a ~ b | c)
produces a number of scatterplots of a against b for given values of c. If c is a
factor, this simply means that a is plotted against b for every level of c. When c is
118

numeric, it is divided into a number of conditioning intervals and for each interval a
is plotted against b for values of c within the interval. The number and position of
intervals can be controlled with [Link]= argument to coplot()—the function
[Link]() is useful for selecting intervals. You can also use two given variables
with a command like
> coplot(a ~ b | c + d)
which produces scatterplots of a against b for every joint conditioning interval
of c and d.
The coplot() and pairs() function both take an argument panel= which can be
used to customize the type of plot which appears in each panel. The default is
points() to produce a scatterplot but by supplying some other low-level graphics
function of two vectors x and y as the value of panel= you can produce any type of
plot you wish. An example panel function useful for coplots is panel. smooth().
Display graphics
Other high-level graphics functions produce different types of plots. Some
examples are:
qqnorm(x)
qqline(x)
qqplot(x, y)
Distribution-comparison plots. The first form plots the numeric vector x
against the expected Normal order scores (a normal scores plot) and the second
adds a straight line to such a plot by drawing a line through the distribution and
data quartiles. The third form plots the quantiles of x against those of y to compare
their respective distributions.
hist(x)
hist(x, nclass=n)
hist(x, breaks=b, …)
Produces a histogram of the numeric vector x. A sensible number of classes is
usually chosen, but a recommendation can be given with the nclass= argument.
Alternatively, the breakpoints can be specified exactly with the breaks= argument.
If the probability=TRUE argument is given, the bars represent relative frequencies
divided by bin width instead of counts.
dotchart(x, …)
Constructs a dotchart of the data in x. In a dotchart the y-axis gives a labelling
of the data in x and the x-axis gives its value. For example it allows easy visual
selection of all data entries with values lying in specified ranges.
image(x, y, z, …)
contour(x, y, z, …)
persp(x, y, z, …)
119

Plots of three variables. The image plot draws a grid of rectangles using
different colours to represent the value of z, the contour plot draws contour lines to
represent the value of z, and the persp plot draws a 3D surface.
Arguments to high-level plotting functions
There are a number of arguments which may be passed to high-level graphics
functions, as follows:
add=TRUE
Forces the function to act as a low-level graphics function, superimposing the
plot on the current plot (some functions only).
axes=FALSE
Suppresses generation of axes—useful for adding your own custom axes with
the axis() function. The default, axes=TRUE, means include axes.
log="x"
log="y"
log="xy"
Causes the x, y or both axes to be logarithmic. This will work for many, but
not all, types of plot.
type=
The type= argument controls the type of plot produced, as follows:
type="p"
Plot individual points (the default)
type="l"
Plot lines

type="b"
Plot points connected by lines (both)

type="o"
Plot points overlaid by lines

type="h"
Plot vertical lines from points to the zero axis (high-density)

type="s"
type="S"
120

Step-function plots. In the first form, the top of the vertical defines the point;
in the second, the bottom.
type="n"
No plotting at all. However axes are still drawn (by default) and the coordinate
system is set up according to the data. Ideal for creating plots with subsequent low-
level graphics functions.
xlab=string
ylab=string
Axis labels for the x and y axes. Use these arguments to change the default
labels, usually the names of the objects used in the call to the high-level plotting
function.
main=string
Figure title, placed at the top of the plot in a large font.
sub=string
Sub-title, placed just below the x-axis in a smaller font.
Low-level plotting commands
Sometimes the high-level plotting functions don’t produce exactly the kind of
plot you desire. In this case, low-level plotting commands can be used to add extra
information (such as points, lines or text) to the current plot.
Some of the more useful low-level plotting functions are:
points(x, y)
lines(x, y)
Adds points or connected lines to the current plot. plot()’s type= argument can
also be passed to these functions (and defaults to "p" for points() and "l" for lines().)
text(x, y, labels, …)
Add text to a plot at points given by x, y. Normally labels is an integer or
character vector in which case labels[i] is plotted at point (x[i], y[i]). The default is
1:length(x).
Note: This function is often used in the sequence
> plot(x, y, type="n"); text(x, y, names)
The graphics parameter type="n" suppresses the points but sets up the axes,
and the text() function supplies special characters, as specified by the character
vector names for the points.
abline(a, b)
abline(h=y)
abline(v=x)
abline([Link])
121

Adds a line of slope b and intercept a to the current plot. h=y may be used to
specify y-coordinates for the heights of horizontal lines to go across a plot, and v=x
similarly for the x-coordinates for vertical lines. Also [Link] may be list with a
coefficients component of length 2 (such as the result of model-fitting functions,)
which are taken as an intercept and slope, in that order.
polygon(x, y, …)
Draws a polygon defined by the ordered vertices in (x, y) and (optionally) shade
it in with hatch lines, or fill it if the graphics device allows the filling of figures.
legend(x, y, legend, …)
Adds a legend to the current plot at the specified position. Plotting characters,
line styles, colors etc., are identified with the labels in the character vector legend.
At least one other argument v (a vector the same length as legend) with the
corresponding values of the plotting unit must also be given, as follows:
legend( , fill=v) - Colors for filled boxes
legend( , col=v) - Colors in which points or lines will be drawn
legend( , lty=v) - Line styles
legend( , lwd=v) - Line widths
legend( , pch=v) - Plotting characters (character vector)
title(main, sub) - Adds a title main to the top of the current plot in a large font
and (optionally) a sub-title sub at the bottom in a smaller font.
axis(side, …)
Adds an axis to the current plot on the side given by the first argument (1 to 4,
counting clockwise from the bottom.) Other arguments control the positioning of
the axis within or beside the plot, and tick positions and labels. Useful for adding
custom axes after calling plot() with the axes=FALSE argument.
Low-level plotting functions usually require some positioning information (e.g.,
x and y coordinates) to determine where to place the new plot elements.
Coordinates are given in terms of user coordinates which are defined by the
previous high-level graphics command and are chosen based on the supplied data.
Where x and y arguments are required, it is also sufficient to supply a single
argument being a list with elements named x and y. Similarly a matrix with two
columns is also valid input. In this way functions such as locator() (see below) may
be used to specify positions on a plot [Link] font.
5.3.3 PACKAGES
All R functions and datasets are stored in packages. Only when a package is
loaded are its contents available. This is done both for efficiency (the full list would
take more memory and would take longer to search than a subset), and to aid
package developers, who are protected from name clashes with other code. The
process of developing packages is described in Creating R packages in Writing R
Extensions. Here, we will describe them from a user’s point of view.
122

To see which packages are installed at your site, issue the command
> library()
with no arguments. To load a particular package (e.g., the boot package
containing functions from Davison & Hinkley (1997)), use a command like
> library(boot)
Users connected to the Internet can use the [Link]() and
[Link]() functions (available through the Packages menu in the Windows
and macOS GUIs, see Installing packages in R Installation and Administration) to
install and update packages.
To see which packages are currently loaded, use
> search()
to display the search list. Some packages may be loaded but not available on
the search list (see Namespaces): these will be included in the list given by
> loadedNamespaces()
To see a list of all available help topics in an installed package, use
> [Link]()
to start the HTML help system, and then navigate to the package listing in the
Reference section.
 Standard packages
 Contributed packages and CRAN
 Namespaces
Standard packages
The standard (or base) packages are considered part of the R source code.
They contain the basic functions that allow R to work, and the datasets and
standard statistical and graphical functions that are described in this manual. They
should be automatically available in any R installation. See R packages in R FAQ,
for a complete list.
Contributed packages and CRAN
There are thousands of contributed packages for R, written by many different
authors. Some of these packages implement specialized statistical methods, others
give access to data or hardware, and others are designed to complement textbooks.
Some (the recommended packages) are distributed with every binary distribution of
R. Most are available for download from CRAN ([Link] and
its mirrors) and other repositories such as Bioconductor
([Link] The R FAQ contains a list of CRAN packages
current at the time of release, but the collection of available packages changes very
frequently.
123

Namespaces
Packages have namespaces, which do three things: they allow the package
writer to hide functions and data that are meant only for internal use, they prevent
functions from breaking when a user (or other package writer) picks a name that
clashes with one in the package, and they provide a way to refer to an object within
a particular package.
For example, t() is the transpose function in R, but users might define their
own function named t. Namespaces prevent the user’s definition from taking
precedence, and breaking every function that tries to transpose a matrix.
There are two operators that work with namespaces. The double-colon
operator :: selects definitions from a particular namespace. In the example above,
the transpose function will always be available as base::t, because it is defined in
the base package. Only functions that are exported from the package can be
retrieved in this way.
The triple-colon operator ::: may be seen in a few places in R code: it acts like
the double-colon operator but also allows access to hidden objects. Users are more
likely to use the getAnywhere() function, which searches multiple packages.
Packages are often inter-dependent, and loading one may cause others to be
automatically loaded. The colon operators described above will also cause
automatic loading of the associated package. When packages with namespaces are
loaded automatically they are not added to the search list.
5.4 REVISION POINTS
Linear models: describe a continuous response variable as a function of one
or more predictor variables. They can help you understand and predict the behavior
of complex systems or analyze experimental, financial, and biological data. Linear
regression is a statistical method used to create a linear model.
Standard Deviation: The Standard Deviation is a measure of how spread out
numbers are. The formula is easy: it is the square root of the Variance.
Variance: The Variance is defined as: The average of the squared differences
from the Mean.
5.5 INTEXT QUESTIONS
1. What is statistical model?
2. How do define statistical model?
3. Define linear models.
4. What are the generic functions for extracting model information?
5. List the families of generalized linear models.
6. What are the three groups of plotting commands?
7. What is the use of plot() function?
8. Name some of the low-level plotting commands.

You might also like