R Matrices
A matrix organizes values into a fixed grid of rows and columns, all of a single data type, making it R's basic tool for two-dimensional data.
Creating a Matrix
A matrix is built with the matrix() function, which takes a vector of values plus the number of rows and columns you want them arranged into. R fills the grid column by column unless you tell it otherwise.
Example
m <- matrix(1:6, nrow = 2, ncol = 3)
m
m2 <- matrix(1:6, nrow = 2, byrow = TRUE)
m2Naming Rows and Columns
Just like vectors, matrices can carry labels. rownames() and colnames() let you attach names to the rows and columns after a matrix is created, which makes the data much easier to read and reference.
Adding Names
sales <- matrix(c(120, 85, 200, 150), nrow = 2)
rownames(sales) <- c("North", "South")
colnames(sales) <- c("Q1", "Q2")
salesAccessing Elements
You reach into a matrix with two indices inside a single set of brackets: matrix[row, column]. Leaving one side blank grabs the entire row or column, and you can use the names you assigned instead of numeric positions too.
Indexing a Matrix
sales <- matrix(c(120, 85, 200, 150), nrow = 2,
dimnames = list(c("North", "South"), c("Q1", "Q2")))
sales[1, 2]
sales["South", ]
sales[, "Q1"]- sales[1, 2] - the value in row 1, column 2
- sales[1, ] - the entire first row as a vector
- sales[, 2] - the entire second column as a vector
- sales["South", "Q2"] - the value at that named row and column
Exercise: R Matrices
What restriction applies to the data stored inside a single R matrix?