0% found this document useful (0 votes)
9 views41 pages

List Matrix

The document provides a comprehensive guide on lists and matrices in R programming. It covers creating, accessing, manipulating, merging lists, and converting lists to vectors, as well as creating and accessing matrices, including their dimensions and manipulations. Key functions like 'list()', 'unlist()', and 'matrix()' are explained with examples to illustrate their usage.

Uploaded by

hridaan939
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views41 pages

List Matrix

The document provides a comprehensive guide on lists and matrices in R programming. It covers creating, accessing, manipulating, merging lists, and converting lists to vectors, as well as creating and accessing matrices, including their dimensions and manipulations. Key functions like 'list()', 'unlist()', and 'matrix()' are explained with examples to illustrate their usage.

Uploaded by

hridaan939
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Lists in R-Programming

 Creating List
 Naming elements in a list(Assigning Names to
elements in a list)
 Accessing elements in a list
 Manipulating elements in a list-Addition,Deletion and
updation of elements in a list
 Subsetting the list elements
 Converting List to Vector:
Lists:
A list in R is a type of R object which
contains different types of elements like
- numbers, vectors, strings, and another
list within it. A list can also contain a
function or a matrix as its elements
--> Single dimensional object
with hetrogeneous data types
--> To create a list use function
list().
# Create a list containing character, complex,
double, integer and logical.
a <- list(“R-STUDIO",2+3i,10,20L,TRUE)

# to check the internal storage of a


typeof(a)
# to check the internal storage of each
value in a
lapply(a,typeof) # list of values
sapply(a,typeof) # vector of values
Lists are the R objects which contain elements of
different types like
Characters
Complex
Double
Integer
Logical
Vector
Matrix
Function and
another list inside it
# Create a list containing
vectors
a <-
list(c(1,2,3),c("A","B","C"),c("R","Python",“Rstudio"),c(1
0000,8000,6000))
print(a)
typeof(a)
lapply(a,typeof)
# Create a list containing characters, vector,
double
b <- list(“DPS
sharjah",“DataScience",c(10,20,30),15.5)
print(b)
typeof(b)
# Create a list containing a vector, matrix, fucntion
lapply(b,typeof)
and list.
c <-
list(c(10,20,30),matrix(c(1,2,3,4),nrow=2),search(),lis
t("DataScience",5345352))
print(c)
typeof(c)
lapply(c,typeof)
Naming elements in a list
names() function
a <-
list(c(1,2,3),c("A","B","C"),c(“ML","Python"
,
"Rstudio"),c(10000,8000,6000))
names(a)<-
c("Sno","Students",“Course","PRices")
print(a)
Practice and save to your
machine
Accessing elements in a list
Elements in a list can be accessed using the index of the element
in the list. In case the
list is a named list, it can also be accessed using the names.

sales1 <-
list(10,"DataScience","Udemy",1800,"3Months")
length(sales1)#output is 5
sales1[1]
sales1[c(1,2,3)]
sales1[1:3]
sales1[-4]
sales1[c(-1,-5)]
sales1[-c(1,5)]
sales1 <-
list(10,"DataScience","Udemy",1800,"3Months")
names(sales1) <-
c("cid","cname","trainer","fee","duration")
names(sales1)
sales1[1]
sales1["cid"]
sales1$cid
sales1[3]
sales1["trainer"]
sales1$trainer
sales1[T]
sales1[c(T,F,T,F,T)]
Manipulating List Elements:
 in vector we can add, delete & update elements.
a <- c(10,20,30)
print(a)
# Add a new element at the end of the vector by using position
a[4] <- 40
print(a)
# Update the 2nd element of the vector by using position
a[2] <- 2
print(a)
# Delete the 2nd element of the vector by using position
a <- a[-2]
print(a)
a <- c(10,20,30)
names(a) <- c("A","B","C")
# Add a new element at the end of the vector by using name
a["D"] <- 40
print(a)
# Update the 2nd element of the vector by using name
a["B"] <- 2
print(a
 Similary in list also we can add, delete & update
elements.

sales1 <-
list(10,"DataScience",“Udemy",1800,"3Months")
names(sales1) <-
# Add a new element at the end of the list by using
c("cid","cname","trainer","fee","duration")
position
sales1[6] <- “Dubai"
sales1[6]
print(sales1)
# Update the 2nd element of the list by using
position
sales1[2] <- "DataAnalysis"
sales1[2]
print(sales1)
# Add a new element at the end of the list by
using name
sales1$Address <- “Dubai"
sales1$Address
print(sales1)
# Delete the last element of the list by using name
sales1$Address <- NULL
sales1$Address
print(sales1)
# Update the 2nd element of the list by using name
sales1$cname <- "MachineLearning"
sales1$cname
print(sales1)
Merging Lists:
==============
--> We can merge many lists into one list by using
list() function
# First create the two lists
a <- list(10,20,30,40)
b <- list("A","B","C","D")
e <- c(a[c(1,4)],b[c(1,4)])
# Merge the a and b lists
print(e)
c <- c(a,b)
f <- c(a[1:3],b[2:4])
print(c)
print(f)
typeof(c)
g <- c(a[-4],b[-1])
d <- c(a[1],b[2])
print(g)
print(d)
Converting List to Vector:
==========================
--> for doing future manipulation it is better to convert
the list into a vector.
--> Arithmetic operations can be applied on the
vectors.
--> to convert the list into vector we have to use
unlist() function.
--> unlist() takes the inputs as list and produces a
a <- list(seq(10,50,10)) # Convert the lists to vectors
b <- list(seq(60,100,10)) c <- unlist(a)
print(a) d <- unlist(b)

print(b) print(c)
print(d)
typeof(a)
typeof(c)
typeof(b)
typeof(d)
# Once observe this manipulation in vector, what will
happen
a <- c(10,20,30)
names(a) <- c("A","B","C")
a["D"] <- 40
print(a)
typeof(a)
a$E <- 50
print(a)
typeof(a)
a <- unlist(a)
# Return a list
a <- list(x=1,y=2)
a[1]
a["x"]
# Return only element in list
a[[1]]
a[["a"]]
YOU HAVE TWO LISTS, LIST1 CONTAINING NUMBERS 1
TO 3 AND LIST2 CONTAINING LETTERS "A", "B", "C".
COMBINE THESE LISTS INTO A NEW LIST COMBINED LIST
AND PRINT IT.

Answer:

list1<-list(1,2,3)
list2<-list("A","B","C")
com_list<-list(c(list1,list2))
com_list
You are given a list that contains information about employees in different departments
of a company. Each department has its own list, which includes the names and salaries
of the employees. Your task is to:
Extract the salaries of each department using unlist().

company <- list(


list(DepartmentName = "HR", Salaries = list(50000, 55000, 52000)),
list(DepartmentName = "IT", Salaries = list(70000, 72000, 68000)),
list(DepartmentName = "Finance", Salaries = list(60000, 62000, 64000))
)
company
unlist(company[[1]]$Salaries)
unlist(company[[2]]$Salaries)
unlist(company[[3]]$Salaries)
Matrices in R programming
In R, matrices are an extension of the
numeric or character vectors.
In other words, they are atomic vectors
arranged in a two-dimensional rectangular
layout.
Thus, matrix being an atomic vector
extension, its elements must be of same
data type.
To create a matrix in R, we use the matrix()
function.
The syntax for creating a matrix in R is:
matrix(data, nrow, ncol, byrow, dimnames)
Ex:
a<-
matrix(c(1,2,3,4,5,6),nrow=2,ncol=3,byrow=F)
The parameters used can be described as follows:
• data: the input vector which becomes the data
elements of the matrix.
• nrow: number of rows to be created.
• ncol: number of columns to be created.
• byrow represents a logical clue.
When set to TRUE, then the elements in input
vector are organized by row.
• dimname is the names assigned to the rows and
# Create a matrix only with data
matrix(data=c(1,2,3,4))
# Here data is optional
matrix(c(1,2,3,4))
# Create a matrix with data, number of rows and number of columns
matrix(c(1,2,3,4,5,6),nrow=2,ncol=3))
# Here nrow or ncol one is enough. both nrow and ncol are not
mandatory
matrix(c(1,2,3,4,5,6),nrow=2)
# Like vectors matrices can be stored as variables and then called later.
a <- matrix(c(1,2,3,4,5,6),nrow=2)
# Here nrow or ncol one is enough. both nrow and ncol are not
mandatory
matrix(c(1,2,3,4,5,6),nrow=2)
# Like vectors matrices can be stored as variables and then called later.
a <- matrix(c(1,2,3,4,5,6),nrow=2)
# Elements are arranged by row
matrix(1:10, nrow=5,
byrow=TRUE)
# Elements are arranged by
column
matrix(1:10, nrow=5,
byrow=FALSE)
matrix(1:10, ncol=5, byrow=T)
# Create a matrix with row names and column
names
matrix(1:10, ncol=5, byrow=TRUE,
1. dimnames=list(c("A","B"),c("C","D","E","F","G
")))
matrix(1:10, ncol=5, byrow=TRUE,
dimnames=list(LETTERS[1:2],LETTERS[3:7]))
# Create a matrix by defining row names and
column names

rownames<-c("Row1","Row2")
colnames<-c("col1","col2","col3","col4","col5")a<-
matrix(1:10,ncol=5,byrow=T,dimnames=list(rowna
mes,colnames))a

# Remove the row names and column names


rownames(a) <- NULL
print(a)
# Remove the row names and column names
rownames(a) <- NULL
colnames(a) <- NULL
print(a)

# Create a matrix without argument names


matrix(1:10,2)
matrix(1:10,5)
matrix(1:10,2,5)
matrix(1:10,2,5,T)
matrix(1:10,2,5,T,list(c("a","b")))
Create a matrix shown below and give rownames and
colnames

Access the element at 2nd column, 1st row,2nd row


Transpose:
----------
The transpose (reversing rows and columns) is
perhaps the simplest method of reshaping a dataset.
Use the t() function to transpose a matrix.
a <- matrix(1:9,nrow=3)
print(a)
t(a)
Matrix with heterogenous data elements would be converted to homogenous data type
based on priority
----------
# Create some matrices with hetrogenous datatype
elements and observe
a <- matrix(c(1,2,3,"A","B","C"),2)
print(a)
typeof(a)
a <- matrix(c("Data",2+3i,TRUE,20,30L,FALSE),3)
print(a)
typeof(a)
a <- matrix(c(TRUE,20,30L,FALSE),2)
print(a)
typeof(a
Matrix with heterogenous data elements would
be converted to homogenous data type based
on priority
----------
# Create a matrix which is not multiple of the
no. of rows and columns
a <- matrix(1:3,3,3)
a <- matrix(1:3,3,3,T)
a <- matrix(1:5,2,3) # Warning Message
a <- matrix(1:5,2,5)
a <- matrix(1:5,2,3) # Warning Message
a <- matrix(1:10,2,5)
a <- matrix(1:10,3,4) # Warning Message
a <- matrix(1:10,5,4)
Accessing Matrix Elements:
==========================
 Elements of a matrix can be accessed by using the column
and row index[position] of the element.

a <- matrix(1:12,3)
print(a)
# Access the element at 1st column and 1st row
a[1]
a[1,1]
3.Given a matrix M with integers from 1 to 9,
extract the element in
a. the second row and third column.
b. the entire second row
c. the third column
# Access the element at 2nd column, 1st row,2nd row and
3rd row
a[c(1,2,3),2]
a[1:3,2]
# Access the element at 2nd column, 1st row and 3rd row
a[c(1,3),2]
# Access the element at 1st row, 2nd & 3rd column
a[1,2:3]
a[1,c(2,3)]
# Access the element at 2nd & 3rd row, 2nd & 3rd column
a[2:3,2:3]
# Access the element at 1st & 3rd row, 1st & 3rd column
a[c(1,3),c(1,3)]
# Access only the 1st row
a[1,1:4]
a[1,]
# Access only the 3rd column
a[1:3,3]
a[,3]
# Access the element at 2nd & 3rd column, all rows
except 2nd row
a[-2,2:3]
Dimensions of a Matrix:
-----------------------
--> Retrieve or set the dimension of an object.
--> We have to use
dim(x)
dim(x) <- value
# to check the dimensions of a matrix
dim(a)
Matrix Manipulations:
=====================
--> We can perform mathematical operations on the
matrices.
--> The result of the operation is also a matrix
--> The number of rows and columns (dimensions) should
be same for
the matrices.
a <- matrix(1:9,3)
b <- matrix(11:19,3)
# Add the matrices
c <- a + b
print(c)

You might also like