Matrix (R)

A matrix is a two-dimensional, rectangular array in R where every element is the same type. It is a vector with a dim (dimension) attribute giving it rows and columns.

R

A matrix arranges elements of one atomic type into rows and columns. You build one with matrix(data, nrow, ncol), and by default R fills it column by column (set byrow = TRUE to fill by rows). Because it's really a vector plus dimensions, matrix operations are vectorized and fast.

Index with two subscripts m[row, col]; leave one blank to take a whole row or column (m[2, ] is row 2). R supports true linear-algebra operations: %*% is matrix multiplication, t() transposes, solve() inverts, and many statistical routines work on matrices directly.

The key contrast is with a data frame: a matrix is single-type and ideal for numeric/linear-algebra work, while a data frame allows different types per column and suits mixed tabular data. An array generalizes a matrix to more than two dimensions.

Syntax

m <- matrix(1:6, nrow = 2, ncol = 3)
m[1, 2]

Examples

R

m <- matrix(1:6, nrow = 2)
print(m)
print(t(m))

Output:

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
     [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    5    6

See also

Back to the Dictionary