0% found this document useful (0 votes)
17 views39 pages

R Programming LAB Manual

Uploaded by

pareshkumar3108
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
17 views39 pages

R Programming LAB Manual

Uploaded by

pareshkumar3108
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 39

Ex.

No:1

Built in functions
Aim:

Calculate the cumulative sum(“running total”)of the numbers 2,3,4,5,6

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

1.2) Print the 1 to 10 numbers in reverse order.

Description: rev is used to reverse the input given


Solution:

>rev(1:10)

Output: 10 9 8 7 6 5 4 3 2 1 1

Viva Questions:

1. Which function is used to find cumulative sum in R?

Ans: cumsum() function in R Language is used to calculate the cumulative sum of the vector
passed as argument.

2.How to print reverse order of numbers in R?

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.

 Using readline() method


 Using scan() method
In R language readline() method takes input in string format. If one inputs an integer then it is
inputted as a string, lets say, one wants to input 255, then it will input as “255”, like a string. So
one needs to convert that inputted value to the format that he needs. In this case, string “255” is
converted to integer 255

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:

Input your name:

Input your age:

[1] "My name is aditya and I am 20 years old."

[1] "R version 4.0.3 (2020-10-10)"

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:

name = "R programming";

n1 = 1;

n2 = 1.5

nums = c(1, 2, 30, 4, 5, 60)

print(ls())

print("Details of the objects in memory:")

print(ls.str())

Output:

[1] "n1" "n2" "name" "nums"

[1] "Details of the objects in memory:"

n1 : num 1

n2 : num 1.5

name : chr "R programming"

nums : num [1:6] 1 2 30 4 5 60

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.

Description:seq( ) is used to print numbers in sequence order

The simplest way to create a sequence of numbers in R is by using the : operator by seq.

Solution:

print("Sequence of numbers from 20 to 50:")

print(seq(20,50))

print("Mean of numbers from 20 to 60:")

print(mean(20:60))

print("Sum of numbers from 51 to 91:")

print(sum(51:91))

Output:

[1] "Sequence of numbers from 20 to 50:"

[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] "Mean of numbers from 20 to 60:"[1] 40

[1] "Sum of numbers from 51 to 91:"

[1] 2911

Viva Questions:

1.How to take multiple inputs in R?

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

2.What is scan method in R?

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

3.How to create sequence of numbers in R?

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

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.

Syntax: barplot(data, xlab, ylab)

where:

 data is the data vector to be represented on y-axis

 xlab is the label given to x-axis

 ylab is the label given to y-axis

Solution:

marks = c(70, 95, 80, 74)

barplot(marks,

main = "Comparing marks of 5 subjects",

xlab = "Marks",

ylab = "Subject",

names.arg = c("English", "Science", "Math.", "Hist."),

col = "darkred",
5
horiz = FALSE)

Output:

Viva Question:

1.What is the syntax to draw barplot?

Ans: barplot(data, xlab, ylab)

2.What are the features of BarPlot?

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

Single Element Vector

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.

# Atomic vector of type character.

print("abc");

# Atomic vector of type double.

print(12.5)

Solution:

str1 = "The quick brown fox jumps over the lazy dog."

print("Original vector(string)")

print(str1)

print("Unique elements of the said vector:")

print(unique(tolower(str1)))

nums = c(1, 2, 2, 3, 4, 4, 5, 6)

print("Original vector(number)")

print(nums)

print("Unique elements of the said vector:")

print(unique(nums))

7
Output:

[1] "Original vector(string)"

[1] "The quick brown fox jumps over the lazy dog."

[1] "Unique elements of the said vector:"

[1] "the quick brown fox jumps over the lazy dog."

[1] "Original vector(number)"

[1] 1 2 2 3 4 4 5 6

[1] "Unique elements of the said vector:"

[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("Content of the said matrix:")

print(m)

Output:

[1] "Content of the said matrix:"

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

for (i in 1:5) l[[i]] <- c(i, 1:4)

print("List of vectors:")

print(l)

result = do.call(rbind, l)

print("New Matrix:")

print(result)

Output:

[1] "List of vectors:"

[[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] "New Matrix:"

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

[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

2.How to Access vector elements?

Ans: Accessing Vector Elements

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.

3.How to sort a vector?

Ans: Elements in a vector can be sorted using the sort() function.

VJAC

10

11
Ex.No:5

Vectors
Aim:

5.1) Write a R program to append value to a given empty vector.

Description: Using append()


We can add data by using the append() function.
Syntax:
append(vector_name,value)

Solution:

# create an empty numeric

# vector a

a=c()

# display it

print(a)

# append 10 using append()

# 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:

Vector() function is also used to create empty vector.

Syntax:

vector(class of the data object, length of the vector)

There is a very straightforward approach for this.

Steps –

 Create vector of required type

 Also pass the size to it

 Here we can also check the type and size of the vector so created

Solution:

x = c(10, 20, 30)


y = c(20, 10, 40)
print("Original Vectors:")
print(x)
print(y)
print("Product of two Vectors:")
z=x*y
print(z)

Output:
[1] "Original Vectors:"

[1] 10 30 6

[1] 20 10 40

[1] "Product of two Vectors:"

[1] 200 300 240

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:

 mean() function is used to calculate mean

Syntax: mean(x, na.rm)

Parameters:

 x: Numeric Vector

 na.rm: Boolean value to ignore NA value

 sum() is used to calculate sum

Syntax: sum(x)

Parameters:

 x: Numeric Vector

 prod() is used to calculate product

Syntax: prod(x)

Parameters:

 x: Numeric Vector

Solution:

x = c(10, NULL, 20, 30, NA)


print("Sum:")
#ignore NA and NaN values
print(sum(x, na.rm=TRUE))
print("Mean:")
print(mean(x, na.rm=TRUE))
print("Product:")
print(prod(x, na.rm=TRUE))
14
Output:
[1] "Sum:"
[1] 60
[1] "Mean:"
[1] 20
[1] "Product:"
[1] 6000

Viva Questions:

1.Which function is used to find mean value?

Ans:mean()

2. Which function is used to find sum?

Ans: sum() is used to calculate sum

3.How to append the vector?


Ans: append(vector_name,value)

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:

[1] "5 × 4 matrix:"


[,1] [,2] [,3] [,4]
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 13 18
[4,] 4 9 14 19
[5,] 5 10 15 20
[1] "3 × 3 matrix with labels, filled by rows: "
Col1 Col2 Col3
Row1 1 3 5
Row2 7 8 9
Row3 11 12 14

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

2. Explain about “initialize()” function in R?

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?

Let’s say this is our vector->

a<-c(1,2,3,4,5,6,7,8,9)

To convert this into a time series object->

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

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


[1,] 1 4 7 10 13
[2,] 2 5 8 11 14
[3,] 3 6 9 12 15

,,2

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


[1,] 16 19 22 25 28
[2,] 17 20 23 26 29
[3,] 18 21 24 27 30
Viva Questions:

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

2. What is the difference between Matrix and an array?

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:

[1] "Original data frame:"

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

[1] "Duplicate elements of the said data frame:"

[1] FALSE FALSE TRUE FALSE FALSEFALSE TRUE FALSE

[1] "Unique rows of the said data frame:"

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:

[1] "Original dataframe:"

name score attempts qualify

1 Anastasia 12.5 1 yes

2 Dima 9.0 3 no

3 Katherine 16.5 2 yes

25
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

size isdir mode mtimectime

data.rda 303 FALSE 666 2022-03-25 11:24:32 2022-03-25 11:24:32

atime exe

data.rda 2022-03-25 11:24:32 no

Viva Questions:

1. What is a data frame?

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.

2. What is the lapply() function in R?

Answer: lapply() function is used when we want to apply a function to each

3. Differentiate between lapply and sapply

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.

# 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:

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] "Red" "Green" "Black"


27
[[2]]

[,1] [,2] [,3]

[1,] 1 5 9

[2,] 3 7 11

[[3]]

[[3]][[1]]

[1] "Python"

[[3]][[2]]

[1] "PHP"

[[3]][[3]]

[1] "Java"

[1] "List with column names:"

$Color

[1] "Red" "Green" "Black"

$`Odd numbers`

[,1] [,2] [,3]

[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

[1] "Red" "Green" "Black"

[1] "2nd element:"

$`Odd numbers`

[,1] [,2] [,3]

[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]]

[1] "Red" "Green" "Black"

[[2]]

[,1] [,2] [,3]

[1,] 1 5 9

[2,] 3 7 11

[[3]]

[[3]][[1]]

[1] "Python"
29
[[3]][[2]]

[1] "PHP"

[[3]][[3]]

[1] "Java"

[1] "Remove the second element of the list:"

[1] "New list:"

[[1]]

[1] "Red" "Green" "Black"

[[2]]

[[2]][[1]]

[1] "Python"

[[2]][[2]]

[1] "PHP"

[[2]][[3]]

[1] "Java"

10.3) Write a R program to select second element of a given nested list.

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] "Original nested list:"

[[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] "Second element of the nested list:"

[[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] "Original lists:"

[[1]]

[1] 1

[[2]]

[1] 2

[[3]]

[1] 3

[[1]]

[1] "Red"

[[2]]
32
[1] "Green"

[[3]]

[1] "Black"

[1] "Merge the said lists:"

[1] "New merged list:"

[[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("Sequence of 15 capital letters, starting from ‘E’-")

print(s)

Output:

[1] "Sequence of 15 capital letters, starting from ‘E’-"

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

list1 = list(g1 = 1:10, g2 = "R Programming", g3 = "HTML")

print("Original list:")

print(list1)

names(list1) = c("a", "b", "c")

print("Assign new names 'a', 'b' and 'c' to the elements of the said list")

print(list1)

Output:

[1] "Original list:"$g1

[1] 1 2 3 4 5 6 7 8 9 10

$g2

[1] "R Programming"

$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

[1] "R Programming"

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

2.How to name a list?

Ans: The list elements can be given names and they can be accessed using these names.

# Create a list containing a vector, a matrix and a list.

list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2),

list("green",12.3))

# Give names to the elements in the list.

names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")

# Show the list.

print(list_data)

35
Ex.No:12

Array
Aim:

12.1) Write a R program to find the levels of factor of a given vector.

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] "Original vector:"

[1] 1 2 3 3 4 NA 3 2 4 5 NA 5

[1] "Levels of factor of the said vector:"

[1] "1" "2" "3" "4" "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:

[1] "Original vector:"

[1] "March" "April" "January" "November" "January"

[6] "September" "October" "September" "November" "August"

[11] "February" "January" "November" "November" "February"

[16] "May" "August" "February" "July" "December"

[21] "August" "August" "September" "November" "September"

[26] "February" "April"

[1] "Ordered factors of the said vector:"

[1] March April January November January September

[7] October September November August February January

[13] November November February May August February

[19] July December August August September November

[25] September February April

11 Levels: April August December February January July March ... September

April August December February January July March

2 4 1 4 3 1 1

May November October September

1 5 1 4

12.3) Write a R program to concatenate two given factor in a single factor.

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] "Original factors:"

[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] "After concatenate factor becomes:"

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

2.How to Generate factor levels?

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

15)consider A=matrix(c(2,0,1,3),ncol-2)and B=matrix(c(5,2,4,-1),ncol=2)


a.find A+B
b.find A-B
Solution:
A = matrix(c(2,0,1,3), ncol=2)
B = matrix(c(5,2,4,-1), ncol=2)

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:

v<-1:100 # Let k value be 100


v
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
## [18] 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
## [35] 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
## [52] 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
## [69] 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
## [86] 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

39

You might also like