In R, a matrix is a two-dimensional array-like structure, where each element of the matrix must be of the same mode (numeric, character, etc). To create a matrix in R, use the matrix()
function:
main.r126 chars6 lines
main.r60 chars5 lines
To access elements of a matrix, use indexing similar to that of a vector, where the row and column are specified within square brackets:
main.r67 chars3 lines
main.r6 chars2 lines
Matrices can be manipulated using a variety of built-in functions and operators, including arithmetic and algebraic operations (+
, -
, *
, %*%
), transposition (t()
), and subsetting functions (rowSums()
, colSums()
, rowMeans()
, and colMeans()
).
main.r212 chars13 lines
Arrays can also be used to create multidimensional matrices in R, where each element has a corresponding row, column, and "layer" (or third dimension). However, the use of arrays is less common in R than matrices, due to the complexity of working with arrays.
gistlibby LogSnag