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

Statistical Computing and R Programming-Unit-I-Notes

The document provides an overview of basic R programming concepts, including assignment operators, vectors, and matrix operations. It covers functions for creating sequences, sorting, indexing, and manipulating lists and matrices, along with examples for clarity. Additionally, it highlights the differences between base R graphics and ggplot2, as well as the use of attributes and class functions.

Uploaded by

navyashettyajpla
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 views23 pages

Statistical Computing and R Programming-Unit-I-Notes

The document provides an overview of basic R programming concepts, including assignment operators, vectors, and matrix operations. It covers functions for creating sequences, sorting, indexing, and manipulating lists and matrices, along with examples for clarity. Additionally, it highlights the differences between base R graphics and ggplot2, as well as the use of attributes and class functions.

Uploaded by

navyashettyajpla
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

Statistical Computing and R Programming

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> x = x + 1 # this overwrites the previous value of x


R> x
[1] -4

2. What is vector? Give an example to create a vector?


A vector is a collection of observations or measurements concerning a single variable.
Example, the heights of 50 people or the number of coffees you drink daily. Here height and number of
coffee are single variables which can have (store) multiple values of same type.
The function for creating a vector is c() [which is a primitive function – ―combine‖] with the desired
entries in parentheses separated by commas.
Example:
R> myvec <- c(1,3,1,42)
R> myvec
[1] 1 3 1 42

3. How do you find length of a vector? Give an example.


length() function is used with reference to vectors to determine how many entries exist in a vector, given
as the argument x.
Example
R> length(x=c(3,2,8,1))
[1] 4

R> length(x=5:13)
[1] 9

4. How do you sort a vector in descending order? Give an example


sort function is used for sorting a vector in increasing or decreasing order of its elements.
Example:
To sort a vector in descending order,
R> sort(x=c(2.5,-1,-10,3.44),decreasing=TRUE)
[1] 3.44 2.50 -1.00 -10.00
Create and store a sequence of values from 5 to −11 that progresses in steps of 0.3
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.

R> seq(from = 5,to = -11,by = -0.3) #specify step size 0.3


[1] 5.0 4.7 4.4 4.1 3.8 3.5 3.2 2.9 2.6 2.3 2.0 1.7
[13] 1.4 1.1 0.8 0.5 0.2 -0.1 -0.4 -0.7 -1.0 -1.3 -1.6 -1.9
[25] -2.2 -2.5 -2.8 -3.1 -3.4 -3.7 -4.0 -4.3 -4.6 -4.9 -5.2 -5.5
[37] -5.8 -6.1 -6.4 -6.7 -7.0 -7.3 -7.6 -7.9 -8.2 -8.5 -8.8 -9.1
[49] -9.4 -9.7 -10.0 -10.3 -10.6 -10.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.

>myvect<-c(5, -3,4,4,4,8,10,40221, -8)


> len<-length(x=myvect)
> myvect[-len]
[1] 5 -3 4 4 4 8 10 40221

6. Write the purpose of negative indexing in vectors? Give an example.


The negative index drops the element at the specified index position, counting from the start position.
Syntax: x[()]
Specifies the index location of the element we wish to remove
Example:
> myvec <- c(5,-2.3,4,4,4,6,8,10,40221,-8)
> myvec[-c(2,4)]
[1] 5 4 4 6 8 10 40221 -8

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

9. How do you find the dimension of the matrix? Give an example


Function dim provides the dimensions of a matrix stored in your workspace. dim always supplies the
number of rows first, followed by the number of columns.
Example:
R> mymat <- rbind(c(1,3,4),5:3,c(100,20,90),11:13)
R> mymat
[,1] [,2] [,3]
[1,] 1 3 4
[2,] 5 4 3
[3,] 100 20 90
[4,] 11 12 13
R> dim(mymat)
[1] 4 3

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

11. What is the use of diag command in R? Give an example.


diag command/function is used to identify the values along the diagonal of a square matrix.
Example
> A <- matrix(c(0.3,4.5,55.3,91,0.1,105.5,-4.2,8.2,27.9),nrow=3,ncol=3)
> diag(x=A)
[1] 0.3 0.1 27.9
This returns a vector with the elements along the diagonal of A, starting at A[1,1].

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

> B[,3] <- B[3,]


>B
[,1] [,2] [,3]
[1,] 0.3 1 55.3
[2,] 2.0 2 30.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> t(A) #transpose function


[,1] [,2]
[1,] 2 6
[2,] 5 1
[3,] 2 4
Inverse of a matrix
R function solve is one option for inverting a matrix.
R> A <- matrix(data=c(3,4,1,2),nrow=2,ncol=2)
R> A
[,1] [,2]
[1,] 3 1
[2,] 4 2

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

> bar <- c(F,T,F,T,F,F,F,F,T,T,T,T)


> bar
[1] FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE

The result of the comparison.


R> foo&bar
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 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"

18. What is list in R? Give an example.


The list is a data structure which can store multiple types of values at once. List can contain any mix of R
structures and objects such as a numeric matrix, a logical array, a single character string, and a factor
object. To create a list, list() function is used.
Here is an example:
R> foo <- list(matrix(data=1:4,nrow=2,ncol=2),c(T,F,T,T),"hello")
R> foo
[[1]]
[,1] [,2]
[1,] 1 3
[2,] 2 4
[[2]]
[1] TRUE FALSE TRUE TRUE
[[3]]
[1] "hello"

19. What is list slicing in lists? Give an example.


List slicing is the method of selecting multiple list items at once.
Example: Suppose now you want to access the second and third components of foo and store them as one
object.
> foo <- list(matrix(data=1:4,nrow=2,ncol=2),c(T,F,T,T),"hello you")
> bar <- foo[c(2,3)]
> bar
[[1]]
[1] TRUE FALSE TRUE TRUE
[[2]]
[1] "hello you!"

20. How do you name list contents? Give an example.


You can name list components to make the elements more recognizable and easy to work with. This can
be done using names() function and passing list name.
Example:
R> names(foo) <- c("mymatrix","mylogicals","mystring")
R> foo
$mymatrix
[,1] [,2]
[1,] 1 3
[2,] 2 4
$mylogicals
[1] TRUE FALSE TRUE TRUE
$mystring
[1] "hello you!"
21. What is the purpose of attributes and class functions? Give an example.
attributes() function is used to print the explicit attributes of any object.
Example:
R> foo <- matrix(data=1:9,nrow=3,ncol=3)
R> foo
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
R> attributes(foo)
$dim
[1] 3 3
The class of a given object can always be retrieved using the class function.
> [Link] <- c("a","few","strings","here")
> [Link] <- c(T,F,F,F,T,F,T,T)
> [Link] <- factor(c("Blue","Blue","Green","Red","Green","Yellow"))
> class([Link])
[1] "character"
> class([Link])
[1] "logical"
> class([Link])
[1] "factor"

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

R> baz <- myvec[-c(2,4)]


R> baz
[1] 5 4 4 6 8 10 40221 -8

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

5. Do the following operations on a square matrix.


a. Retrieve third and first rows of A, in that order, and from those rows, second and third column
elements.
b. Retrieve diagonal elements
c. Delete second column of the matrix.

Consider a 3x3 matrix A <- matrix(c(0.3,4.5,55.3,91,0.1,105.5,-4.2,8.2,27.9),nrow=3,ncol=3)


[,1] [,2] [,3]
[1,] 0.3 91.0 -4.2
[2,] 4.5 0.1 8.2
[3,] 55.3 105.5 27.9

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

b. Retrieve diagonal elements


R> diag(x=A)
[1] 0.3 0.1 27.9

c. Delete second column of the matrix.


R> A[,-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> A <- rbind(c(2,5,2),c(6,1,4))


R> A
[,1] [,2] [,3]
[1,] 2 5 2
[2,] 6 1 4

R> t(A)
[,1] [,2]
[1,] 2 6
[2,] 5 1
[3,] 2 4

b) Scalar Multiple of a Matrix


Multiplication of any matrix A by a scalar value a results in a matrix in which every individual
element is multiplied by a scalar value. A scalar value is just a single, univariate value.
Here’s an example:

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

c) Matrix Addition and Subtraction


Addition or subtraction of two matrices of equal size is also performed in an element-wise fashion.
Corresponding elements are added or subtracted from one another, depending on the operation.
Here’s an example:
You can add or subtract any two equally sized matrices with the standard + and - symbols.
R> A <- cbind(c(2,5,2),c(6,1,4))
R> A
[,1] [,2]
[1,] 2 6
[2,] 5 1
[3,] 2 4
R> B <- cbind(c(-2,3,6),c(8.1,8.2,-9.8))
R> B
[,1] [,2]
[1,] -2 8.1
[2,] 3 8.2
[3,] 6 -9.8
R> A-B
[,1] [,2]
[1,] 4 -2.1
[2,] 2 -7.2
[3,] -4 13.8

8. How do you create arrays in R? Explain with suitable example


Array can be considered to be a collection of equally dimensioned matrices, providing a
rectangular prism of elements. A three dimensional array has a fixed number of rows and a fixed
number of columns, as well as a new third dimension called a layer.

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

Logical operators used in R


Logicals are especially useful when you want to examine whether multiple conditions are satisfied.
Often you’ll want to perform certain operations only if a number of different conditions have been
met. The previous section looked at relational operators, used to compare the literal values (that is,
numeric or otherwise) of stored R objects. Now you’ll look at logical operators, which are used to
compare two TRUE or FALSE objects.

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 !

R> cat("The value stored as 'a' is ",a,".",sep="")


The value stored as 'a' is 3.

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."

12. Write a note on escape sequences with example.


A stand-alone backslash (\) doesn’t act like a normal character within a string. The \ is used to
invoke an escape sequence. An escape sequence lets you enter characters that control the format
and spacing of the string, rather than being interpreted as normal text. The following Table
describes some of the most common escape sequences

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.

R> cat("here is a string\nsplit\tto neww\b\n\n\tlines")


here is a string
split to new
lines

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!"\"

Substitution is more flexible using the functions sub and gsub.


The sub function searches a given string x for a smaller string pattern contained within. It then
replaces the first instance with a new string, given as the argument replacement.
Here’s an example:

R> bar <- "How much wood could a woodchuck chuck"


R> sub(pattern="chuck",replacement="hurl",x=bar)
[1] "How much wood could a woodhurl chuck"

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.

R> mob <- c("Apr","Jan","Dec","Sep","Nov","Jul","Jul","Jun")


R> ms <- c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov", "Dec")
R> [Link] <- factor(x=mob,levels=ms,ordered=TRUE)
R> [Link]
[1] Apr Jan Dec Sep Nov Jul Jul Jun
Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < Oct < Nov < Dec

16. Explain cut function on factors with an example.


Cut function is used to fit a data set into discrete factor categories.
Factors are also often created from data that was originally measured on a continuum, for example
the weight of a set of adults or the amount of a drug given to a patient. Sometimes you’ll need to
group (or bin) these types of observations into categories, like Small/Medium/Large or Low/High.
In R, you can mold this kind of data into discrete factor categories using the cut function.
Consider the following numeric vector of length 10:
R> Y <- c(0.53,5.4,1.5,3.33,0.45,0.01,2,4.2,1.99,1.01)
Suppose you want to bin the data as follows: Small refers to observations in the interval [0;2),
Medium refers to [2;4), and Large refers to [4; 6). A square bracket refers to inclusion of its nearest
value, and a parenthesis indicates exclusion, so an observation y will fall in the Small interval if 0
<= y < 2, in Medium if 2 <= y < 4, or in Large if 4 <= y < 6.
For this you’d use cut and supply your desired break intervals to the breaks argument:
R> br <- c(0,2,4,6)
R> cut(x=Y,breaks=br)
[1] (0,2] (4,6] (0,2] (2,4] (0,2] (0,2] (0,2] (4,6] (0,2] (0,2]
Levels: (0,2] (2,4] (4,6]

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.

person age sex


Peter 42 M
Lois 40 F
Meg 17 F
Chris 14 M
Stewie 1 M

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

b) To extract the elements of age column using dollar operator.


R> mydata$age
[1] 42 40 17 14 1

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.

Add more records (adding to the number of rows)


For example, suppose you had another record to include in mydata: the age and sex of another
individual, Brian.
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)

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

Now, you can simply call the following:


R> mydata <- rbind(mydata,newrecord)
R> mydata
person age sex
1 Peter 42 M
2 Lois 40 F
3 Meg 17 F
4 Chris 14 M
5 Stewie 1 M
6 Brian 7 M

To add a new variable (adding to the number of columns)


Suppose you want to add a new variable to state classification of how funny these six individuals
are, defined as a ―degree of funniness.‖(Low, Med (medium), and High)

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)
R> funny <- c("High","High","Low","Med","High","Med")
R> funny <- factor(x=funny,levels=c("Low","Med","High"))
You can use cbind to append this factor vector as a column to the existing mydata.
R> mydata <- cbind(mydata,funny)
R> mydata
person age sex funny
1 Peter 42 M High
2 Lois 40 F High
3 Meg 17 F Low
4 Chris 14 M Med
5 Stewie 1 M High
6 Brian 7 M Med

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.

R> foo <- NaN


R> foo
[1] NaN
R> bar <- c(NaN,54.3,-2,NaN,90094.123,-Inf,55)
R> bar
[1] NaN 54.30 -2.00 NaN 90094.12 -Inf 55.00
Typically, NaN is the unintended result of attempting a calculation that’s impossible to perform
with the specified values

 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 Object-Checking Functions


Identifying the class of an object is essential for functions that operate on stored objects, especially
those that behave differently depending on the class of the object. To check whether the object is a
specific class or data type, you can use the is-dot functions on the object and it will return a TRUE
or FALSE logical value.

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

As-Dot Coercion Functions


Converting from one object or data type to another is referred to as coercion. Like other features of
R you’ve met so far, coercion is performed either implicitly or explicitly. Implicit coercion occurs
automatically when elements need to be converted to another type in order for an operation to
complete. In other situations, coercion won’t happen automatically and must be carried out by the
user. This explicit coercion can be achieved with the as-dot functions.
Examples:
R> [Link](c(T,F,F,T))
[1] 1 0 0 1
R> 1:4+[Link](c(T,F,F,T))
[1] 2 2 3 5
R> foo <- 34
R> [Link] <- [Link](foo)
R> [Link]
[1] "34"

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")

Aesthetic mapping with geoms


Geoms and ggplot2 also provide efficient, automated ways to apply different styles to different
subsets of a plot. If you split a data set into categories using a factor object, ggplot2 can
automatically apply particular styles to different categories. In ggplot2’s documentation, the factor
that holds these categories is called a variable, which ggplot2 can map to aesthetic values. This gets
rid of much of the effort that goes into isolating subsets of data and plotting them separately using
base R graphics.
Now, let’s replot these data using the same qplot object along with a suite of geom modifications in
order to get something more like Figure 7-6.

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.

You might also like