Statistical Computing and R Programming-Unit-I-Notes
Statistical Computing and R Programming-Unit-I-Notes
Unit-I
Two mark questions
1. What are the two ways of assignment operators in R? Give an example.
An assignment in R can be used in two ways: using arrow notation (<-) and using a single equal sign (=).
Both methods are shown here:
R> x <- -5 # this assigns a value to x
R> x
[1] -5
R> length(x=5:13)
[1] 9
5. Let vector, myvect with elements 5, -3, 4, 4, 4, 8, 10, 40221, -8, 1. Write code to delete last element
from it.
7. If baz <- c(1,-1,0.5,-0.5) and qux <- 3, find the value of baz+qux.
>baz <- c(1,-1,0.5,-0.5)
> qux <- 3
> baz+qux
Output:
[1] 4.0 2.0 3.5 2.5
8. What is the use of cbind and rbind functions in Matrix? Give an example
rbind command binds together the vectors as rows of a matrix, with the top-to-bottom order of the rows
matching the order of the vectors supplied to rbind.
Example:
R> rbind(1:3,4:6)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
cbind command binds together the vectors as columns of a matrix, in the order they were supplied, and
each vector becomes a column of the resulting matrix. Example:
R> cbind(c(1,4),c(2,5),c(3,6))
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
10. Construct a 4 × 2 matrix that is filled row-wise with the values 4.3, 3.1, 8.2, 8.2, 3.2, 0.9, 1.6,
and 6.5, in that order using R command.
> mat<-c(4.3, 3.1, 8.2, 8.2, 3.2, 0.9, 1.6, 6.5)
> matrix(mat,,nrow=4,ncol=2)
[,1] [,2]
[1,] 4.3 3.2
[2,] 3.1 0.9
[3,] 8.2 1.6
[4,] 8.2 6.5
12. Write proper code to replace the third column of matrix B with the values in the third row of B.
> A<-c(0.3, 2.0, 55.3,1.0, 2.0, 30.0, 50.0, 23.0, 27.9)
> B <- matrix(A,nrow=3,ncol=3)
>B
[,1] [,2] [,3]
[1,] 0.3 1 50.0
[2,] 2.0 2 23.0
[3,] 55.3 30 27.9
13. Write an example to find transpose and inverse of a matrix using R command?
Transpose of a matrix
R> A <- rbind(c(2,5,2),c(6,1,4))
R> A
[,1] [,2] [,3]
[1,] 2 5 2
[2,] 6 1 4
R> solve(A)
[,1] [,2]
[1,] 1 -0.5
[2,] -2 1.5
14. What is the difference between & and && in R? Give an example.
The difference between & and && in R is -
& - are meant for element-wise comparisons
&& - meant for comparing two individual values and will return a single logical value
Example:
> foo <- c(T,F,F,F,T,F,T,T,T,F,T,F)
> foo
[1] TRUE FALSE FALSE FALSE TRUE FALSE TRUE TRUE TRUE FALSE TRUE FALSE
R> foo&&bar
[1] FALSE
15. Write R command to store the vector c(8,8,4,4,5,1,5,6,6,8) as bar. Identify the elements less than
or equal to 6 AND not equal to 4.
> bar<- c(8,8,4,4,5,1,5,6,6,8)
> bar[(bar!=4)&(bar<=6)]
[1] 5 1 5 6 6
16. How do you count the number of individual characters in a string? Give an example.
To count the number of individual characters, you can use the nchar function. Here’s an example using
foo:
R> foo <- "This is a character string!"
R> foo
[1] "This is a character string!"
R> nchar(x=foo)
[1] 27
17. What is levels function in R? Give an example
A level is a component which stores the possible values in the factor.
Information stores in levels can be extracted as a vector of character strings using the levels function.
Here’s an example:
> batch<-factor(x=c("male","female","female","male","female","male","female"))
> levels(x=batch)
[1] "female" "male"
22. What is the difference between ggplot2 and base R graphics created plots? Give an example.
The base R graphis is R’s built-in graphical tools. plot()is a simple graphics function which takes in two
vectors—one vector of x locations and one vector of y locations—and opens a built in graphics device
where it displays the result.
R> foo <- c(1.1,2,3.5,3.9,4.2)
R> bar <- c(2,2.2,-1.3,0,0.2)
R> plot(foo,bar)
ggplot2 is a popular data visualization package based on grammar of graphics contributed by Hadley
Wickham, which provides a programmable interface to create complex plots.
Example.
R> foo <- c(1.1,2,3.5,3.9,4.2)
R> bar <- c(2,2.2,-1.3,0,0.2)
You can produce ggplot2’s version using its function qplot.
R> qplot(foo,bar)
_________________
Four or Six marks questions
1. Explain seq, rep and length functions on vectors with example.
a) seq command allows for flexible creations of sequences. This ready-to-use function takes in a
from value, a to value, and a by value, and it returns the corresponding sequence as a numeric
vector.
> seq(from=3,to=27,by=3) #specify step size 3
[1] 3 6 9 12 15 18 21 24 27
b) rep function is used when we want to create a sequence by repeating a value or a group of
values.
> rep(x=1,times=4)
[1] 1 1 1 1
> rep(x=c(3,62,8.3),times=3)
[1] 3.0 62.0 8.3 3.0 62.0 8.3 3.0 62.0 8.3
> rep(x=c(3,62,8.3),each=2)
[1] 3.0 3.0 62.0 62.0 8.3 8.3
c) length function when used with reference to vectors determines how many entries exist in a
vector given as the argument x.
> length(x=c(3,2,8,1))
[1] 4
> length(x=5:13)
[1] 9
2. Repeat the vector c (-1, 3, -5, 7, -9) twice, with each element repeated 10 times, and store
the result. Display the result sorted from largest to smallest.
num<- rep(x=c (-1, 3, -5, 7, -9),each=10,times=2)
sort(x=num,decreasing=TRUE)
Output:
[1] 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
3 3 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
[55] -1 -1 -1 -1 -1 -1 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -9 -9 -9 -9 -9 -9 -9 -9 -9
-9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9
3. How do you extract elements from vectors? Explain it using individual and vector of
indexes with example?
Subsetting is the process of extracting specific elements from a vector using square-bracket
operator. Number as index corresponds to the position of a value within a vector. Using negative
value for index deletes an element. This process of extracting or deleting values from a vector does
not change the original vector you are subsetting unless you explicitly overwrite the vector with the
subsetted version.
Example:
Using individual index
R> myvec <- c(5,-2.3,4,4,4,6,8,10,40221,-8)
R> myvec[1]
[1] 5
R> foo <- myvec[2]
R> foo
[1] -2.3
R> myvec[length(x=myvec)]
[1] -8
Example:
Using multiple indices
R> myvec[c(1,3,5)]
[1] 5 4 4
4. How do you create matrix in R? Explain with its necessary attributes? Give an
example.
A matrix is a collection of vectors of same sizes (equal length) stored together. The size of a matrix
is specified by a number of rows and a number of columns. Matrix A is defined as an m x n matrix;
that is, A will have exactly m rows and n columns.
To create a matrix in R, use matrix command (function), providing the entries of the matrix to the
data argument as a vector.
Syntax: matrix(vector,nrow,ncol)
Here, vector is collection of objects of same type
nrow is number of rows
ncol is number of columns
Example:
R> A <- matrix(data=c(-3,2,893,0.17),nrow=2,ncol=2)
R> A
[,1] [,2]
[1,] -3 893.00
[2,] 2 0.17
Answers
a. Retrieve third and first rows of A, in that order, and from those rows, second and third
column elements.
R> A[c(3,1),2:3]
[,1] [,2]
[1,] 105.5 27.9
[2,] 91.0 -4.2
6. How do you omit and overwrite an element/s from a matrix? Explain with example.
Omit element/s from a matrix
To delete or omit elements from a matrix, you again use square brackets, but with negative indexes.
The following provides A without its second column:
R> A[,-2]
[,1] [,2]
[1,] 0.3 -4.2
[2,] 4.5 8.2
[3,] 55.3 27.9
The following removes the first row from A and retrieves the third and second column values, in
that order, from the remaining two rows:
R> A[-1,3:2]
[,1] [,2]
[1,] 8.2 0.1
[2,] 27.9 105.5
Overwrite an element/s from a matrix
To overwrite particular elements, or entire rows or columns, you identify the elements to be
replaced and then assign the new values. The new elements can be a single value, a vector of the
same length as the number of elements to be replaced, or a vector whose length evenly divides the
number of elements to be replaced. To illustrate this, let’s first create a copy of A and call it B.
R> B <- A
R> B
[,1] [,2] [,3]
[1,] 0.3 91.0 -4.2
[2,] 4.5 0.1 8.2
[3,] 55.3 105.5 27.9
The following overwrites the second row of B with the sequence 1, 2, and 3:
R> B[2,] <- 1:3
R> B
[,1] [,2] [,3]
[1,] 0.3 91.0 -4.2
[2,] 1.0 2.0 3.0
[3,] 55.3 105.5 27.9
The following overwrites the second column elements of the first and third rows with 900:
R> B[c(1,3),2] <- 900
R> B
[,1] [,2] [,3]
[1,] 0.3 900 -4.2
[2,] 1.0 2 3.0
[3,] 55.3 900 27.9
7. Explain any three matrix operations using R commands with example.
a) Matrix Transpose.
For any m x n matrix A, its transpose, AT, is the n x m matrix obtained by writing either its columns
as rows or its rows as columns.
Here’s an example:
R> t(A)
[,1] [,2]
[1,] 2 6
[2,] 5 1
[3,] 2 4
R will perform this multiplication in an element-wise manner, as you might expect. Scalar
multiplication of a matrix is carried out using the standard arithmetic * operator.
R> A <- rbind(c(2,5,2),c(6,1,4))
R> a <- 2
R> a*A
[,1] [,2] [,3]
[1,] 4 10 4
[2,] 12 2 8
To create these data structures in R, use the array function and specify the individual elements in
the data argument as a vector. Then specify size in the dim argument as another vector with a length
corresponding to the number of dimensions. Note that array fills the entries of each layer with the
elements in data in a strict column-wise fashion, starting with the first layer.
Consider the following example:
R> AR <- array(data=1:24,dim=c(3,4,2))
R> AR
,,1
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
,,2
[,1] [,2] [,3] [,4]
[1,] 13 16 19 22
[2,] 14 17 20 23
[3,] 15 18 21 24
This gives you an array of the same size - each of the two layers constitutes a 3 x 4 matrix.
Note the order of the dimensions supplied to dim: c(rows,columns,layers). Just like a single matrix,
the product of the dimension sizes of an array will yield the total number of elements.
9. Explain any three relational and logical operators used in R, with an example.
Relational operators used in R
Logicals are commonly used to check relationships between values. For example, you might want
to know whether some number a is greater than a predefined threshold b. For this, you use the
standard relational operators, which produce logical values as results.
Operator Interpretation
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Here’s an example:
R> 1==2
[1] FALSE
R> 1>2
[1] FALSE
R> (2-1)<=2
[1] TRUE
R> 1!=(2+3)
[1] TRUE
Example:
R> foo <- c(T,F,F,F,T,F,T,T,T,F,T,F)
R> bar <- c(F,T,F,T,F,F,F,F,T,T,T,T)
R> foo&bar
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE TRUE FALSE
R> foo|bar
[1] TRUE TRUE FALSE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE
R> foo&&bar
[1] FALSE
R> foo||bar
[1] TRUE
10. Explain any, all and which functions with example, on logical vector.
There are two useful functions you can use to quickly inspect a collection of logical values:
any and all. When examining a vector, any returns TRUE if any of the logicals in the vector are
TRUE and returns FALSE otherwise.
The function all returns a TRUE only if all of the logicals are TRUE, and returns FALSE
otherwise.
Example:
R> qux <- foo==bar
R> qux
[1] FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE TRUE FALSE
R> any(qux)
[1] TRUE
R> all(qux)
[1] FALSE
The R function which takes in a logical vector as the argument x and returns the indexes
corresponding to the positions of any and all TRUE entries.
R> which(x=c(T,F,F,T,T))
[1] 1 4 5
You can use this to identify the index positions of myvec that meet a certain condition; for example,
those containing negative numbers:
R> myvec <- c(5,-2.3,4,4,4,6,8,10,40221,-8)
R> which(x=myvec<0)
[1] 2 10
To omit the negative entries of myvec, you could execute the following:
R> myvec[-which(x=myvec<0)]
[1] 5 4 4 4 6 8 10 40221
11. Explain cat and paste functions with necessary arguments in R. Give an example.
There are two main functions used to concatenate (or glue together) one or more strings: cat and
paste. The difference between the two lies in how their contents are returned. When calling cat or
paste, you pass arguments to the function in the order you want them combined.
The first function, cat, sends its output directly to the console screen and doesn’t formally return
anything.
R> qux <- c("awesome","R","is")
R> qux
[1] "awesome" "R" "is"
R> cat(qux[2],qux[3],"totally",qux[1],"!")
R is totally awesome !
The paste function concatenates its contents and then returns the final character string as a usable R
object. This is useful when the result of a string concatenation needs to be passed to another
function or used in some secondary way, as opposed to just being displayed. Consider the following
vector of character strings:
R> qux <- c("awesome","R","is")
R> qux
[1] "awesome" "R" "is"
R> paste(qux[2],qux[3],"totally",qux[1],"!")
[1] "R is totally awesome !"
R> paste("The value stored as 'b' is ",b,".",sep="")
[1] "The value stored as 'b' is 4.4."
Escape sequences add flexibility to the display of character strings, which can be useful for
summaries of results and plot annotations. You enter the sequence precisely where you want it to
take effect. Let’s look at an example.
Since the signal for an escape is \ and the signal to begin and end a string is ", if you want
either of these characters to be included in a string, you must also use an escape to have them be
interpreted as a normal character.
R> cat("I really want a backslash: \\\nand a double quote: \"")
I really want a backslash: \
and a double quote: "
14. Explain substr, sub and gsub functions on strings with an example.
Pattern matching lets you inspect a given string to identify smaller strings within it.
The function substr takes a string x and extracts the part of the string between two character
positions (inclusive), indicated with numbers passed as start and stop arguments.
Example:
R> foo <- "This is a character string!"
R> substr(x=foo,start=21,stop=27)
[1] "string!"
Here, you’ve extracted the characters between positions 21 and 27, inclusive, to get "string!".
The function substr can also be used with the assignment operator to directly substitute in a new set
of characters. In this case, the replacement string should contain the same number of characters as
the selected area.
R> substr(x=foo,start=1,stop=4) <- "Here"
R> foo
[1] "Here is a character string!"\"
The gsub function does the same thing, but it replaces every instance of pattern. Here’s an
example:
R> bar <- "How much wood could a woodchuck chuck"
R> gsub(pattern="chuck",replacement="hurl",x=bar)
[1] "How much wood could a woodhurl hurl"
15. What is factor? How do you define and order levels in a factor?
Factors are data structures that store categorical data which are finite in number and are
represented as levels.
Factors are typically created from a numeric or a character vector using factor function. Factors
take the form of vectors.
Example:
>gender<-c(―female‖, ―female‖, ―male‖, ―female‖, ―male‖, ―male‖, ―female‖)
>[Link]<-factor(gender)
>[Link]
[1] female female male female male male female
Levels: female male
Factor objects can be created and order the values precisely as they appear in levels by setting the
argument ordered to TRUE. You can define additional levels by supplying a character vector of all
possible values to the levels argument and then instruct R to order them.
17. What do you mean by member reference in lists? Explain with an example. (4)
Retrieving components from a list using indexes, which are entered in double square brackets, is
known as a member reference.
R> foo <- list(matrix(data=1:4,nrow=2,ncol=2),c(T,F,T,T),"hello")
You can retrieve components from a list using indexes, which are entered in double square
brackets.
R> foo[[1]]
[,1] [,2]
[1,] 1 3
[2,] 2 4
R> foo[[3]]
[1] "hello"
When you’ve retrieved a component this way, you can treat it just like a stand-alone object in the
workspace; there’s nothing special that needs to be done.
R> foo[[1]] + 5.5
[,1] [,2]
[1,] 6.5 8.5
[2,] 7.5 9.5
R> foo[[1]][1,2]
[1] 3
R> foo[[1]][2,]
[1] 2 4
R> cat(foo[[3]],"you!")
hello you!
18. What is data frame? Create a data frame as shown in the given table and write R
commands
a) To extract the third, fourth, and fifth elements of the third column
b) To extract the elements of age column using dollar operator.
A data frame is a data structure for presenting a data set with a collection of recorded observations
(grouped data) for one or more different types of variables. To create a data frame, use the
[Link] function.
Create a data frame as shown in the given table
R> mydata <- [Link](person=c("Peter","Lois","Meg","Chris","Stewie"), age=c(42,40,17,14,1),
sex=factor(c("M","F","F","M","M")), stringsAsFactors=FALSE)
a) To extract the third, fourth, and fifth elements of the third column
R> mydata[3:5,3]
[1] F M M
Levels: F M
19. How do you add data rows or data columns and combine data frames? Explain with
examples.
To add data to an existing data frame, i.e, a set of observations for a new variable (adding to the
number of columns), or it could be more records (adding to the number of rows), you may use
rbind and cbind functions, which let you append rows and columns, respectively. These same
functions can be used to extend data frames intuitively.
The first step is to create a new data frame that contains Brian’s information.
R> newrecord <- [Link](person="Brian",age=7, sex=factor("M",levels=levels(mydata$sex)))
R> newrecord
person age sex
1 Brian 7 M
20. Write a note on special values used in R with an example for each.
Special values used in R are:
Infinity
When a number is too large for R to represent, the value is deemed to be infinite. This value is
represented by the special object Inf, which is case sensitive. Because it represents a numeric value,
Inf can be associated only with numeric vectors.
Let’s create some objects to test it out.
R> foo <- Inf
R> foo
[1] Inf
R> bar <- c(3401,Inf,3.1,-555,Inf,43)
R> bar
[1] 3401.0 Inf 3.1 -555.0 Inf 43.0
R> baz <- 90000^100
R> baz
[1] Inf
R can also represent negative infinity, with -Inf.
R> qux <- c(-42,565,-Inf,-Inf,Inf,-45632.3)
NaN
In some situations, it’s impossible to express the result of a calculation using a number, Inf, or -Inf.
These difficult-to-quantify special values are labeled NaN in R, which stands for Not a Number.
NaN values are associated only with numeric observations.
It’s possible to define or include a NaN value directly, but this is rarely the way they’re
encountered.
NA
In statistical analyses, data sets often contain missing values. For example, someone filling out a
questionnaire may not respond to a particular item, or a researcher may record some observations
from an experiment incorrectly. R provides a standard special term to represent missing values,
NA, which reads as Not Available.
NaN is used only with respect to numeric operations, missing values can occur for any type of
observation. As such, NAs can exist in both numeric and non-numeric settings.
Here’s an example:
R> foo <- c("character","a",NA,"with","string",NA)
R> foo
[1] "character" "a" NA "with" "string" NA
R> bar <- factor(c("blue",NA,NA,"blue","green","blue",NA,"red","red",NA,
"green"))
NULL
NULL value is often used to explicitly define an ―empty‖ entity, which is quite different from a
―missing‖ entity specified with NA. An instance of NA clearly denotes an existing position that can
be accessed and/or overwritten if necessary—not so for NULL. You can see an indication of this if
you compare the assignment of NA with the assignment of a NULL.
R> foo <- NULL
R> foo
NULL
R> bar <- NA
R> bar
[1] NA
21. Explain Is-Dot Object-Checking Functions and As-Dot Coercion Functions with an
example.
Is-dot functions exist for almost any sensible check you can think of. For example, consider the
following six checks:
R> num.vec1 <- 1:4
R> num.vec1
[1] 1 2 3 4
R> [Link](num.vec1)
[1] TRUE
R> [Link](num.vec1)
[1] TRUE
R> [Link](num.vec1)
[1] FALSE
R> [Link](num.vec1)
[1] FALSE
R> [Link](num.vec1)
[1] TRUE
R> [Link](num.vec1)
[1] FALSE
22. List and explain graphical parameters used in plot function in R with example.
Graphical parameters used in plot() function in R, are the following:
type: Tells R how to plot the supplied coordinates (for example, as stand-alone points or joined by
lines or both dots and lines).
main, xlab, ylab: Options to include plot title, the horizontal axis label, and the vertical axis label,
respectively.
col: Color (or colors) to use for plotting points and lines.
pch: Stands for point character. This selects which character to use for plotting individual points.
cex: Stands for character expansion. This controls the size of plotted point characters.
lty: Stands for line type. This specifies the type of line to use to connect the points (for example,
solid, dotted, or dashed).
lwd: Stands for line width. This controls the thickness of plotted lines.
xlim, ylim: This provides limits for the horizontal range and vertical range (respectively) of the
plotting region.
Example
R> foo <- c(1.1,2,3.5,3.9,4.2)
R> bar <- c(2,2.2,-1.3,0,0.2)
R> plot(foo,bar,type="b",main="My lovely plot",xlab="",ylab="", col=6, pch=15, lty=3, cex=0.7,
lwd=2)
23. How do you add Points, Lines, and Text to an existing Plot? Explain with example.
Generally speaking, each call to plot will refresh the active graphics device for a new plotting
region. But this is not always desired—to build more complicated
plots, it’s easiest to start with an empty plotting region and progressively add any required points,
lines, text, and legends to this canvas.
Here are some useful, ready-to-use functions in R that will add to a plot without refreshing or
clearing the window:
points Adds points
lines, abline, segments Adds lines
text Writes text
arrows Adds arrows
legend Adds a legend
The syntax for calling and setting parameters for these functions is the same as plot.
You use points to begin adding specific coordinates from x and y to the plot.
R> points(x[y>=5],y[y>=5],pch=4,col="darkmagenta",cex=2)
To draw lines connecting the coordinates in x and y, you use lines. Here you’ve also set lty to 4,
which draws a dash-dot-dash style line.
R> lines(x,y,lty=4)
As per the default behavior of text, the string supplied as labels is centered on the coordinates
provided with the arguments x and y.
R> text(x=8,y=15,labels="sweet spot")
24. How do you set appearance constants and aesthetic mapping with geoms? Explain with
example.
To add and customize points and lines in a ggplot2 graphic, you alter the object itself, rather than
using a long list of arguments or secondary functions executed separately (such as points or lines).
You can modify the object using ggplot2’s convenient suite of geometric modifiers, known as
geoms.
Example: Let’s say you want to connect the five points in foo and bar with a line.
R> foo <- c(1.1,2,3.5,3.9,4.2)
R> bar <- c(2,2.2,-1.3,0,0.2)
You can first create a blank plot object and then use geometric modifiers on it like this:
R> qplot(foo,bar,geom="blank") + geom_point() + geom_line()
You can control default settings for features, such as color or point/line typefeatures by
specifying optional arguments, as shown here:
R> qplot(foo,bar,geom="blank") + geom_point(size=3,shape=6,color="blue") +
geom_line(color="red", linetype=2)
You could first store the qplot object you created earlier and then use geom_point with that
object to try different point styles.
R> myqplot <- qplot(foo,bar,geom="blank") + geom_line(color="red",linetype=2)
R> myqplot + geom_point(size=3,shape=3,color="blue")
R> myqplot + geom_point(size=3,shape=7,color="blue")
Executing the following produces the plot on the right of Figure 7-11:
Now you have a factor with 20 values sorted into four levels. You’ll use this factor to tell qplot how
to map your aesthetics. Here’s a simple way to do that:
This single line of code produces the left plot in Figure 7-11, which separates the four categories by
color and point character and even provides a legend. This was all done by the aesthetic mapping in
the call to qplot, where you set color and shape to be mapped to the ptype variable.