Introduction to R Programming Basics
Introduction to R Programming Basics
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
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
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
> length(x)
[1] 5
Error in x[c(2, -4)] : only 0's may be mixed with negative subscripts
> 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"
> 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[["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
> 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
> rownames(x)
[1] "X" "Y" "Z"
> 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(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
> 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
> 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
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
> 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
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
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
[1] single divorced <NA> single
Levels: single married divorced
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")
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"
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.
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
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
> 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(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
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
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 * 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
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
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)
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.