Data Structure: Matrix
↪ Creating a matrix
A matrix is a two-dimensional table with rows and columns of data. Like vectors, R matrices can contain one type of data and are typically used for only storing numeric data.
Creating a matrix from two vectors using cbind() function.
x = c(2,3,4,5) y = c(5,6,7,8) z = cbind(x,y) z
---Output--- - x y [1,] 2 5 [2,] 3 6 [3,] 4 7 [4,] 5 8
Creating a matrix with an initial element, say initial element = 1, using the function matrix(initial element, row, column).
z = matrix(1,2,4) z
---Output--- - [,1] [,2] [,3] [,4] [1,] 1 1 1 1 [2,] 1 1 1 1
Creating a matrix from vector using function matrix(vector, row, column).
z = matrix(x,2,2) z
---Output--- - [,1] [,2] [1,] 2 4 [2,] 3 5
Creating a matrix by specifying a number of rows or columns with the vector.
m <- matrix(c(10, 20, 30, 40), nrow = 2) m - [,1] [,2] [1,] 10 30 [2,] 20 40OR
m <- matrix(c(10, 20, 30, 40), ncol = 2) m
R loads the data column by default. This method is called column-major order. This behavior can be overridden by byrow = TRUE while creating the matrix.
m <- matrix(c(10, 20, 30, 40), ncol = 2, byrow=TRUE) m
---Output--- - [,1] [,2] [1,] 10 20 [2,] 30 40
Data Structure: Matrix
↪ Accessing matrix
Accessing matrix row
z[1,]
Accessing matrix column
z[,2]
Accessing matrix element
z[2,2]
Transpose of a matrix
t(z)
Inverse of a matrix
solve(z)