R - Matrices and Lists
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.
We can input matrix elements along the row direction by enabling the by row option.
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
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
2. Matrix Construction
a) Transpose
We construct the transpose of a matrix by interchanging its columns and rows using the function t
b) Combining Matrices
To combine two matrices with same numbres of rows use cbind
To combine two matrices having same numbers of columns use the function rbind
3. Matrix Arithmetics
a) Addition and substraction
We can add or substract two matrices when they have the same dimensions
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.
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
####List Slicing
To retrieve a list slice use the single square bracket “[]” operator.
With an index vector, we can retrieve a slice with multiple list members.
Member access
To directly access a list member, we have to use the double square bracket “[[]]” operator.
2. Named Members
We can assign names to list members and reference them by names instead of numeric indexes.
List Slicing
We retrieve a list slice with the single square bracket “[]” operator.
With an index vector, we can retrive a slice with multiple members
Member Access
We can attach a list to the R search path and access its members without explicitly mentioning the list.