R Matrix Summaries
Matrix summary functions reduce a whole row or column to one number. diag() reads the diagonal line of cells or builds a matrix from it.
Average each row
rowMeans adds each row and divides by the number of columns. The two rows average to 6 and 12.
m <- matrix(c(4, 8, 6, 10, 14, 12), nrow = 2, byrow = TRUE)
print(m)
print(rowMeans(m))Average each column
colMeans adds each column and divides by the number of rows. The three columns average to 7, 11 and 9.
m <- matrix(c(4, 8, 6, 10, 14, 12), nrow = 2, byrow = TRUE)
print(colMeans(m))Read the diagonal
The main diagonal runs from the top left cell downwards. diag reads those cells as a vector.
m <- matrix(c(4, 8, 6, 10, 14, 12), nrow = 2, byrow = TRUE)
print(diag(m))Build an identity matrix
diag with the number 3 builds a square matrix of size three. Ones sit on the diagonal and zeros fill the rest.
print(diag(3))Example
scores <- matrix(c(80, 90, 100, 60, 75, 90), nrow = 2, byrow = TRUE)
print(scores)
print(rowMeans(scores))
print(colMeans(scores))
print(diag(scores))Key points
- rowSums() and colSums() add up each row and each column.
- rowMeans() averages each row into one value per row.
- colMeans() averages each column into one value per column.
- diag() on a matrix reads the cells on the main diagonal.
- diag() with one number builds an identity matrix of that size.
- An identity matrix has ones on the diagonal and zeros elsewhere.
In this example, the rows average to 90 and 75 while the columns average to 70, 82.5 and 95. diag then reads the two diagonal cells, 80 and 75.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does diag(3) build?