R Programming LAB Manual
R Programming LAB Manual
No:1
Built in functions
Aim:
Description: cumsum() function in R Language is used to calculate the cumulative sum of the
vector passed as argument.
Syntax: cumsum(x)
Parameters:
x: Numeric Object
Solution:
>cumsum(2:6)
Output: 2 5 9 14 20
cumsum(1:4)
1 3 6 10
>rev(1:10)
Output: 10 9 8 7 6 5 4 3 2 1 1
Viva Questions:
Ans: cumsum() function in R Language is used to calculate the cumulative sum of the vector
passed as argument.
Ans: rev()
1
Ex.No:2
Basic Programs
Aim: Write a R program to take input from the user (name and age) and display the
values. Also print the version of R installation.
Description: In R it’s also possible to take input from the user. For doing so, there are two
methods in R.
Solution:
name = readline(prompt="Input your name: ")
age = readline(prompt="Input your age: ")
print(paste("My name is",”aditya”, "and I am",20,"years old."))
print(R.version.string)
Output:
2
Aim:Write a R program to get the details of the objects in memory.
Description: To create an object in R, one needs to give it a name followed by the assignment
operator <- (An equal sign, =, can also be used), and the value he wants to give it:
x <- 5
Solution:
n1 = 1;
n2 = 1.5
print(ls())
print(ls.str())
Output:
n1 : num 1
n2 : num 1.5
3
Aim Write a R program to create a sequence of numbers from 20 to 50 and find the mean of
numbers from 20 to 60 and sum of numbers from 51 to 91.
The simplest way to create a sequence of numbers in R is by using the : operator by seq.
Solution:
print(seq(20,50))
print(mean(20:60))
print(sum(51:91))
Output:
[1] 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
[26] 45 46 47 48 49 50
[1] 2911
Viva Questions:
Ans: Taking multiple inputs in R language is same as taking single input, just need to define
multiple readline() for inputs. One can use braces for define multiple readline() inside it
Ans: This method takes input from the console. This method is a very handy method while
inputs are needed to taken quickly for any mathematical calculation or for any dataset
Ans: The simplest way to create a sequence of numbers in R is by using the : operator by seq.
4
Ex.No:3
Graphics
Aim:Write a R program to create a simple bar plot of five subjects marks.
Description : R language is mostly used for statistics and data analytics purposes to represent
the data graphically in the software. To represent those data graphically, charts and graphs are
used in R.
R – graphs
There are hundreds of charts and graphs present in R. For example, bar plot, box plot, mosaic
plot, dot chart, coplot, histogram, pie chart, scatter graph, etc.
Bar plot or Bar Chart in R is used to represent the values in data vector as height of the bars. The
data vector passed to the function is represented over y-axis of the graph. Bar chart can behave
like histogram by using table() function instead of data vector.
where:
Solution:
barplot(marks,
xlab = "Marks",
ylab = "Subject",
col = "darkred",
5
horiz = FALSE)
Output:
Viva Question:
Ans: The features of the bar chart can be expanded by adding more parameters.
The main parameter is used to add title. The col parameter is used to add colors to the bars.
The args.name is a vector having same number of values as the input vector to describe the
meaning of each bar.
6
Ex.No:4
Vectors
Aim: Write a R program to get the unique elements of a given string and unique numbers of
vector.
Description:
Vectors are the most basic R data objects and there are six types of atomic vectors. They are
logical, integer, double, complex, character and raw.
Vector Creation
Even when you write just one value in R, it becomes a vector of length 1 and belongs to one of
the above vector types.
print("abc");
print(12.5)
Solution:
str1 = "The quick brown fox jumps over the lazy dog."
print("Original vector(string)")
print(str1)
print(unique(tolower(str1)))
nums = c(1, 2, 2, 3, 4, 4, 5, 6)
print("Original vector(number)")
print(nums)
print(unique(nums))
7
Output:
[1] "The quick brown fox jumps over the lazy dog."
[1] "the quick brown fox jumps over the lazy dog."
[1] 1 2 2 3 4 4 5 6
[1] 1 2 3 4 5 6
8
Aim. : Write a R program to create three vectors a,b,c with 3 integers. Combine the three vectors
to become a 3×3 matrix where each column represents a vector. Print the content of the matrix
Description:
The cbind function – short for column bind – is a merge function that can be used to combine
two data frames with the same number of multiple rows into a single data frame.
Solution:
a<-c(1,2,3)
b<-c(4,5,6)
c<-c(7,8,9)
m<-cbind(a,b,c)
print(m)
Output:
abc
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
9
Aim: Write a R program to create a matrix from a list of given vectors.
Description:
Solution:
l = list()
print("List of vectors:")
print(l)
result = do.call(rbind, l)
print("New Matrix:")
print(result)
Output:
[[1]]
[1] 1 1 2 3 4
[[2]]
[1] 2 1 2 3 4
[[3]]
[1] 3 1 2 3 4
[[4]]
[1] 4 1 2 3 4
[[5]]
[1] 5 1 2 3 4
[1,] 1 1 2 3 4
[2,] 2 1 2 3 4
[3,] 3 1 2 3 4
10
[4,] 4 1 2 3 4
[5,] 5 1 2 3 4
Viva Questions:
1.What is a vector?
Ans: Vectors are the most basic R data objects and there are six types of atomic vectors. They are
logical, integer, double, complex, character and raw
Elements of a Vector are accessed using indexing. The [ ] brackets are used for indexing.
Indexing starts with position 1. Giving a negative value in the index drops that element from
result.TRUE, FALSE or 0 and 1 can also be used for indexing.
VJAC
10
11
Ex.No:5
Vectors
Aim:
Solution:
# vector a
a=c()
# display it
print(a)
# function
a=append(a,10)
# display
print(a)
Output:
NULL
[1] 10
12
Aim:
5.2) Write a R program to multiply two vectors of integers type and length 3
Description:
Syntax:
Steps –
Here we can also check the type and size of the vector so created
Solution:
Output:
[1] "Original Vectors:"
[1] 10 30 6
[1] 20 10 40
13
Aim:
5.3) Write a R program to find Sum, Mean and Product of a Vector, ignore element like A or NaN.
Description:
sum(), mean(), and prod() methods are available in R which are used to compute the specified
operation over the arguments specified in the method. In case, a single vector is specified, then
the operation is performed over individual elements, which is equivalent to the application of for
loop.
Function Used:
Parameters:
x: Numeric Vector
Syntax: sum(x)
Parameters:
x: Numeric Vector
Syntax: prod(x)
Parameters:
x: Numeric Vector
Solution:
Viva Questions:
Ans:mean()
15
Ex.No:6
Matrices
Aim:
6.1) Write a R program to create a 5 x 4 matrix , 3 x 3 matrix with labels and fill the matrix by
rows and 2 × 2 matrix with labels and fill the matrix by columns.
Descrption:
Matrices are the R objects in which the elements are arranged in a two-dimensional rectangular
layout. They contain elements of the same atomic types. Though we can create a matrix
containing only characters or only logical values, they are not of much use. We use matrices
containing numeric elements to be used in mathematical calculations.
A Matrix is created using the matrix() function.
Syntax
The basic syntax for creating a matrix in R is −
matrix(data, nrow, ncol, byrow, dimnames)
Solution:
m1 = matrix(1:20, nrow=5, ncol=4)
print("5 × 4 matrix:")
print(m1)
cells = c(1,3,5,7,8,9,11,12,14)
rnames = c("Row1", "Row2", "Row3")
cnames = c("Col1", "Col2", "Col3")
m2 = matrix(cells, nrow=3, ncol=3, byrow=TRUE, dimnames=list(rnames, cnames))
print("3 × 3 matrix with labels, filled by rows: ")
print(m2)
print("3 × 3 matrix with labels, filled by columns: ")
m3 = matrix(cells, nrow=3, ncol=3, byrow=FALSE, dimnames=list(rnames, cnames))
print(m3)
Output:
16
[1] "3 × 3 matrix with labels, filled by columns: "
Col1 Col2 Col3
Row1 1 7 11
Row2 3 8 12
Row3 5 9 14
6.2) Write a R program to create a two-dimensional 5x3 array of sequence of even integers
greater than 50.
Solution:
a <- array(seq(from = 50, length.out = 15, by = 2), c(5, 3))
print("Content of the array:")
print("5×3 array of sequence of even integers greater than 50:")
print(a)
Output:
[1] "Content of the array:"
[1] "5×3 array of sequence of even integers greater than 50:"
[,1] [,2] [,3]
[1,] 50 60 70
[2,] 52 62 72
[3,] 54 64 74
[4,] 56 66 76
[5,] 58 68 78
17
6.3) Write a R program to find row and column index of maximum and minimum value in a
given matrix
Solution:
m = matrix(c(1:16), nrow = 4, byrow = TRUE)
print("Original Matrix:")
print(m)
result = which(m == max(m), arr.ind=TRUE)
print("Row and column of maximum value of the said matrix:")
print(result)
result = which(m == min(m), arr.ind=TRUE)
print("Row and column of minimum value of the said matrix:")
print(result)
Output:
[1] "Original Matrix:"
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 5 6 7 8
[3,] 9 10 11 12
[4,] 13 14 15 16
[1] "Row and column of maximum value of the said matrix:"
row col
[1,] 4 4
[1] "Row and column of minimum value of the said matrix:"
row col
[1,] 1 1
Viva:
1.Define matrix?
Ans: A matrix is a two-dimensional data structure. Matrices are used to bind vectors from the
same length. All the elements of a matrix must be of the same type (numeric, logical, character,
complex).
initialize() function is used to initialize the private data members while declaring the object.
3. Given a vector of values, how would you convert it into a time series object?
a<-c(1,2,3,4,5,6,7,8,9)
as.ts(a)->a
18
Ex.No:7
Array
Aim:
7.1) Write a R program to combine three arrays so that the first row of the first array is followed
by the first row of the second array and then first row of the third array.
Description:
Arrays are the R data objects which can store data in more than two dimensions. For example −
If we create an array of dimension (2, 3, 4) then it creates 4 rectangular matrices each with 2
rows and 3 columns. Arrays can store only data type.
An array is created using the array() function. It takes vectors as input and uses the values in
the dim parameter to create an array.
Solution:
num1 = rbind(rep("A",3), rep("B",3), rep("C",3))
print("num1")
print(num1)
num2 = rbind(rep("P",3), rep("Q",3), rep("R",3))
print("num2")
print(num2)
num3 = rbind(rep("X",3), rep("Y",3), rep("Z",3))
print("num3")
print(num3)
a = matrix(t(cbind(num1,num2,num3)),ncol=3, byrow=T)
print("Combine three arrays, taking one row from each one by one:")
print(a)
Output:
[1] "num1"
[,1] [,2] [,3]
[1,] "A" "A" "A"
[2,] "B" "B" "B"
[3,] "C" "C" "C"
[1] "num2"
[,1] [,2] [,3]
[1,] "P" "P" "P"
[2,] "Q" "Q" "Q"
[3,] "R" "R" "R"
[1] "num3"
[,1] [,2] [,3]
[1,] "X" "X" "X"
[2,] "Y" "Y" "Y"
[3,] "Z" "Z" "Z"
19
[1] "Combine three arrays, taking one row from each one by one:"
[,1] [,2] [,3]
[1,] "A" "A" "A"
[2,] "P" "P" "P"
[3,] "X" "X" "X"
[4,] "B" "B" "B"
[5,] "Q" "Q" "Q"
[6,] "Y" "Y" "Y"
[7,] "C" "C" "C"
[8,] "R" "R" "R"
[9,] "Z" "Z" "Z"
20
7.2)Write a R program to create an array using four given columns, three given rows, and two
given tables and display the content of the array.
Solution:
array1 = array(1:30, dim=c(3,5,2))
print(array1)
Output:
,,1
,,2
1. What is an Array?
Answer: Array is a superset of Matrices. On the one hand, the matrices can be of 2 dimensions,
but the array can be of any number of dimensions
Answer: Matrix can have only two dimensions, whereas an array can have as many dimensions
as you want. Matrix is defined with the help of data, number of rows, number of columns, and
whether the elements are to be put in row-wise or column-wise.
In array, you need to give the dimension of the array. An array can be of any number of
dimensions, and each dimension is a matrix. For example, a 3x3x2 array represents two matrices,
each of dimension 3x3.
21
Ex.No:8
Array
Aim:
8.1) Write a R program to create an empty data frame.
Solution:
df = data.frame(Ints=integer(),
Doubles=double(),
Characters=character(),
Logicals=logical(),
Factors=factor(),
stringsAsFactors=FALSE)
print("Structure of the empty dataframe:")
print(str(df))
Output:
[1] "Structure of the empty dataframe:"
'data.frame': 0 obs. of 5 variables:
$ Ints : int
$ Doubles : num
$ Characters: chr
$ Logicals : logi
$ Factors : Factor w/ 0 levels:
NULL
8.2) Write a R program to create a data frame from four given vectors.
Solution:
name = c('Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin',
'Jonas')
score = c(12.5, 9, 16.5, 12, 9, 20, 14.5, 13.5, 8, 19)
attempts = c(1, 3, 2, 3, 2, 3, 1, 1, 2, 1)
qualify = c('yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes')
print("Original data frame:")
print(name)
print(score)
print(attempts)
print(qualify)
df = data.frame(name, score, attempts, qualify)
print(df)
Output:
[1] "Original data frame:"
[1] "Anastasia" "Dima" "Katherine" "James" "Emily" "Michael"
22
[7] "Matthew" "Laura" "Kevin" "Jonas"
[1] 12.5 9.0 16.5 12.0 9.0 20.0 14.5 13.5 8.0 19.0
[1] 1 3 2 3 2 3 1 1 2 1
[1] "yes" "no" "yes" "no" "no" "yes" "yes" "no" "no" "yes"
name score attempts qualify
1 Anastasia 12.5 1 yes
2 Dima 9.0 3 no
3 Katherine 16.5 2 yes
4 James 12.0 3 no
5 Emily 9.0 2 no
6 Michael 20.0 3 yes
7 Matthew 14.5 1 yes
8 Laura 13.5 1 no
9 Kevin 8.0 2 no
10 Jonas 19.0 1 yes
23
Ex.No:9
Data Frame
Aim:
9.1) Write a R program to create a data frame using two given vectors and display the duplicated
elements and unique rows of the said data frame.
Description:
A data frame is a table or a two-dimensional array-like structure in which each column contains
values of one variable and each row contains one set of values from each column.
Following are the characteristics of a data frame.
The column names should be non-empty.
The row names should be unique.
The data stored in a data frame can be of numeric, factor or character type.
Each column should contain same number of data items
Solution:
a = c(10,20,10,10,40,50,20,30)
b = c(10,30,10,20,0,50,30,30)
print("Original data frame:")
ab =data.frame(a,b)
print(ab)
print("Duplicate elements of the said data frame:")
print(duplicated(ab))
print("Unique rows of the said data frame:")
print(unique(ab))
Output:
a b
1 10 10
2 20 30
3 10 10
4 10 20
5 40 0
6 50 50
7 20 30
24
8 30 30
a b
1 10 10
2 20 30
4 10 20
5 40 0
6 50 50
8 30 30
9.2) Write a R program to save the information of a data frame in a file and display the
information of the file.
Solution:
exam_data=data.frame(
name =
c('Anastasia','Dima','Katherine','James','Emily','Michael','Matthew','Laura','Kevin','Jonas'),
score = c(12.5,9,16.5,12,9,20,14.5,13.5,8,19),
attempts = c(1,3,2,3,2,3,1,1,2,1),
qualify = c('yes','no','yes','no','no','yes','yes','no','no','yes'))
print("Original dataframe:")
print(exam_data)
save(exam_data,file="data.rda")
load("data.rda")
file.info("data.rda")
Output:
2 Dima 9.0 3 no
25
4 James 12.0 3 no
5 Emily 9.0 2 no
8 Laura 13.5 1 no
9 Kevin 8.0 2 no
atime exe
Viva Questions:
Answer: The data frame is a list of vectors of equal length. It can consist of any vector with a
particular type and can combine it into one. So, a data frame can have a vector of logical and
another of numeric. The only condition is that all the vectors should have the same length.
Answer: If the programmers want the output to be a data frame or a vector, then the sapply
function is used, whereas if a programmer wants the output to be a list, then lapply is used.
26
Ex.No:10
List
Aim:
10.1) Write a R program to create a list containing a vector, a matrix and a list and give names to
the elements in the list. Access the first and second element of the list.
Description:
Lists are the R objects which contain elements of different types like − numbers, strings, vectors
and another list inside it. A list can also contain a matrix or a function as its elements. List is
created using list() function.
Creating a List
Following is an example to create a list containing strings, numbers, vectors and a logical values.
# values.
print(list_data)
Solution:
list_data<-list(c("Red","Green","Black"), matrix(c(1,3,5,7,9,11),nrow=2),
list("Python","PHP","Java"))
print("List:")
print(list_data)
names(list_data)= c("Color","Odd numbers","Language(s)")
print("List with column names:")
print(list_data)
print('1st element:')
print(list_data[1])
print('2nd element:')
print(list_data[2])
output:
[1] "List:"
[[1]]
[1,] 1 5 9
[2,] 3 7 11
[[3]]
[[3]][[1]]
[1] "Python"
[[3]][[2]]
[1] "PHP"
[[3]][[3]]
[1] "Java"
$Color
$`Odd numbers`
[1,] 1 5 9
[2,] 3 7 11
$`Language(s)`
$`Language(s)`[[1]]
[1] "Python"
$`Language(s)`[[2]]
[1] "PHP"
$`Language(s)`[[3]]
[1] "Java"
28
[1] "1st element:"
$Color
$`Odd numbers`
[1,] 1 5 9
[2,] 3 7 11
10.2) Write a R program to create a list containing a vector, a matrix and a list and remove the
second element.
Solution:
list_data<-list(c("Red","Green","Black"), matrix(c(1,3,5,7,9,11),nrow=2),
list("Python","PHP","Java"))
print("List:")
print(list_data)
print("Remove the second element of the list:")
list_data[2]= NULL
print("New list:")
print(list_data)
Output:
[1] "List:"
[[1]]
[[2]]
[1,] 1 5 9
[2,] 3 7 11
[[3]]
[[3]][[1]]
[1] "Python"
29
[[3]][[2]]
[1] "PHP"
[[3]][[3]]
[1] "Java"
[[1]]
[[2]]
[[2]][[1]]
[1] "Python"
[[2]][[2]]
[1] "PHP"
[[2]][[3]]
[1] "Java"
Solution:
x =list(list(0,2),list(3,4),list(5,6))
print("Original nested list:")
print(x)
e =lapply(x,'[[',2)
print("Second element of the nested list:")
print(e)
Output:
[[1]]
[[1]][[1]]
[1] 0
30
[[1]][[2]]
[1] 2
[[2]]
[[2]][[1]]
[1] 3
[[2]][[2]]
[1] 4
[[3]]
[[3]][[1]]
[1] 5
[[3]][[2]]
[1] 6
[[1]]
[1] 2
[[2]]
[1] 4
[[3]]
[1] 6
31
Ex.No:11
Lists
11.1) Write a R program to merge two given lists into one list.
Description:
Lists are the R objects which contain elements of different types like − numbers, strings, vectors
and another list inside it. A list can also contain a matrix or a function as its elements. List is
created using list() function.
Creating a List
Following is an example to create a list containing strings, numbers, vectors and a logical values.
# Create a list containing strings, numbers, vectors and a logical
# values.
list_data <- list("Red", "Green", c(21,32,11), TRUE, 51.23, 119.1)
print(list_data)
Solution:
n1 =list(1,2,3)
c1 =list("Red","Green","Black")
print("Original lists:")
print(n1)
print(c1)
print("Merge the said lists:")
mlist= c(n1, c1)
print("New merged list:")
print(mlist)
Output:
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[1]]
[1] "Red"
[[2]]
32
[1] "Green"
[[3]]
[1] "Black"
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] "Red"
[[5]]
[1] "Green"
[[6]]
[1] "Black"
33
11.2)
Aim:Write a R program to create a list named s containing sequence of 15 capital letters, starting
from ‘E’.
Solution:
s = LETTERS[match("E", LETTERS):(match("E", LETTERS)+15)]
print(s)
Output:
[1] "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T"
11.3) Write a R program to assign new names "a", "b" and "c" to the elements of a given list.
print("Original list:")
print(list1)
print("Assign new names 'a', 'b' and 'c' to the elements of the said list")
print(list1)
Output:
[1] 1 2 3 4 5 6 7 8 9 10
$g2
$g3
[1] "HTML"
[1] "Assign new names 'a', 'b' and 'c' to the elements of the said list"
$a
34
[1] 1 2 3 4 5 6 7 8 9 10
$b
$c
[1] "HTML"
Viva questions:
1.What is a list?
Ans: Lists are the R objects which contain elements of different types like − numbers, strings,
vectors and another list inside it. A list can also contain a matrix or a function as its elements.
List is created using list() function.
Ans: The list elements can be given names and they can be accessed using these names.
list("green",12.3))
print(list_data)
35
Ex.No:12
Array
Aim:
Description:
Arrays are the R data objects which can store data in more than two dimensions. For example −
If we create an array of dimension (2, 3, 4) then it creates 4 rectangular matrices each with 2
rows and 3 columns. Arrays can store only data type.
An array is created using the array() function. It takes vectors as input and uses the values in
the dim parameter to create an array.
Solution:
v = c(1,2,3,3,4, NA,3,2,4,5, NA,5)
print("Original vector:")
print(v)
print("Levels of factor of the said vector:")
print(levels(factor(v)))
Output:
[1] 1 2 3 3 4 NA 3 2 4 5 NA 5
12.2) Write a R program to create an ordered factor from data consisting of the names of months.
Solution:
mons_v= c("March","April","January","November","January",
"September","October","September","November","August","February",
"January","November","November","February","May","August","February",
"July","December","August","August","September","November","September",
"February","April")
print("Original vector:")
print(mons_v)
f = factor(mons_v)
print("Ordered factors of the said vector:")
print(f)
print(table(f))
36
Output:
11 Levels: April August December February January July March ... September
2 4 1 4 3 1 1
1 5 1 4
Solution:
f1 <- factor(sample(LETTERS, size=6, replace=TRUE))
f2 <- factor(sample(LETTERS, size=6, replace=TRUE))
print("Original factors:")
print(f1)
print(f2)
f = factor(c(levels(f1)[f1], levels(f2)[f2]))
print("After concatenate factor becomes:")
print(f)
37
Output:
[1] F E P C B I
Levels: B C E F I P
[1] Z J I J G E
Levels: E G I J Z
[1] F E P C B I Z J I J G E
Levels: B C E F G I J P Z
Viva Questions:
1.What is a factor?
Ans: Factors are the data objects which are used to categorize the data and store it as levels. They can
store both strings and integers. They are useful in the columns which have a limited number of unique
values. Like "Male, "Female" and True, False etc. They are useful in data analysis for statistical
modeling.
Factors are created using the factor () function by taking a vector as input.
Ans: We can generate factor levels by using the gl() function. It takes two integers as input
which indicates how many levels and how many times each level.
38
Augmented Experiments:
13)Aim:
The number below are the first ten days of rain fall amounts in 1996.
Read them into a vector using c() function 0.1,0.6,33.8,1.9,9.6,4.3,33.7,0.3,0.0,0.1
Inspect the data and answer the following questions:
a.what was the mean rainfall,how about the standard deviation?
b.calculate the cumulative rainfall(“running total”)over these ten days.confirm
that the last value of the vector that this produces is equal to the total sum of
the rainfall.
c.which day saw the highest rainfall?hintwhich.max()
Solution:
Rainfall<-c(0.1,0.6,33.8,1.9,9.6,4.3,33.7,0.3,0.0,0.1)
Output:
0.1,0.6,33.8,1.9,9.6,4.3,33.7,0.3,0.0,0.1
A+B
16)Consider a vector 1:K,where K is a positive integer.Write an R command that
determines how many elements in the vector are exactly divisible by 3.
Solution:
39