A. Matrices

A matrix is a collection of data elements arranged in a two-dimensional rectangular layout.

1. Matrix Elements

The elements in a matrix must be all of the same basic type. By default, matrix elements are arranged along the column direction.

    a <- matrix(c(2,1,4,5,3,7), nrow =2)

We can input matrix elements along the row direction by enabling the by row option.

    b <- matrix(c(2,1,4,5,3,7), nrow =2, byrow = TRUE)

A matrix of M rows and N columns is called a M x N matrix. An element at the mth row and nth column can be accessed via

    a[m,n]

The entire mth row can be extracted as a[m,]. The entire nth column can be extracted as a[,n] These return a vector. To return a matrix use drop=False as argument.

If we assign names to the rows and columns, then we can access matrix elements by names instead of coordinates

a["row2","col3"]

2. Matrix Construction

a) Transpose

We construct the transpose of a matrix by interchanging its columns and rows using the function t

t(a)

b) Combining Matrices

To combine two matrices with same numbres of rows use cbind

cbind(b,c)

To combine two matrices having same numbers of columns use the function rbind

rbind(b,d)

3. Matrix Arithmetics

a) Addition and substraction

We can add or substract two matrices when they have the same dimensions

a+b

b) Multiplication

We can multiply two matrices together if the column dimension of the firt matrix is the same as the row dimension of the second madtrx.

a%*%b

Useful links:

B. Lists

A list is a generic vector containing other objects. It allows objects of differente data type to reside together in the same container.

1. List Index

n <- c(2,3,5)
s <- c("a","b","c","d")
b <- c(TRUE,FALSE,TRUE,FALSE)

x <- list(n,s,b,3)

####List Slicing

To retrieve a list slice use the single square bracket “[]” operator.

    x[2]

With an index vector, we can retrieve a slice with multiple list members.

    x[c(2,4)]

Member access

To directly access a list member, we have to use the double square bracket “[[]]” operator.

    x[[2]]

2. Named Members

We can assign names to list members and reference them by names instead of numeric indexes.

    v <- list(peter = c(2,3,5), john= c("aa", "bb"))

List Slicing

We retrieve a list slice with the single square bracket “[]” operator.

    v["peter"]

With an index vector, we can retrive a slice with multiple members

   v[c("peter","john")]

Member Access

v <- [["peter"]]

v$peter

We can attach a list to the R search path and access its members without explicitly mentioning the list.

attach(v)
    peter  ## output: c(2,3,5)
detach(v)  ## should be explicitly detached for cleanup