A matrix is a 2-dimensional array with \(m\) rows and \(n\) columns. All elements in a matrix have the same underlying type (numeric, character, logical, …).
Use matrix():
Key arguments: - data: vector (or other object) used to
fill the matrix - nrow: number of rows - ncol:
number of columns - byrow: if FALSE (default)
fill column-wise; if TRUE fill row-wise
## [,1] [,2]
## [1,] 1 2
## [2,] 3 4
## [3,] 5 6
## [4,] 7 8
## [5,] 9 10
## [1] 5 2
## [,1] [,2]
## [1,] 1 6
## [2,] 2 7
## [3,] 3 8
## [4,] 4 9
## [5,] 5 10
## [1] 5 2
Use square brackets [row, col]. A comma separates row
selection from column selection.
Examples: - m[1, 2] selects row 1, column 2. -
m[1:3, 2:3] selects rows 1–3 and columns 2–3. -
m[, 1] selects all rows in column 1. - m[1, ]
selects all columns in row 1.
## [,1] [,2] [,3]
## [1,] 1 5 9
## [2,] 2 6 10
## [3,] 3 7 11
## [4,] 4 8 12
## [,1] [,2] [,3]
## [1,] 1 5 9
## [2,] 2 6 10
## [3,] 3 7 11
## [4,] 4 8 12
## [,1] [,2]
## [1,] 5 9
## [2,] 6 10
## [3,] 7 11
## [1] 1 2 3 4
## [1] 1 5 9
A work by Gianluca Sottile
gianluca.sottile@unipa.it