Lists, Matrices, and Tables
Matrices
Rows and Columns
A matrix stores one data type in two dimensions. Column functions summarize values by column.
Program
Play the script to build a two-row matrix and choose the last column total.
matrices.R
Replay: real traced execution (multi-file project)
grid <- matrix(1:6, nrow = 2)
column_totals <- colSums(grid)
last_total <- column_totals[3]
cat(last_total, "\n", sep = "")
grid ← 2 x 3 matrix
1grid <- matrix(1:6, nrow = 2)2column_totals <- colSums(grid)values this step2 x 3 matrixgridcolumn_totals ← 3, 7, 11
1grid <- matrix(1:6, nrow = 2)2column_totals <- colSums(grid)3last_total <- column_totals[3]values this step3, 7, 11column_totals1+2, 3+4, 5+6grid columnslast_total ← 11
2column_totals <- colSums(grid)3last_total <- column_totals[3]4cat(last_total, "\n", sep = "")values this step11last_total11column_totals[3]cat(last_total, " ", sep = "")
3last_total <- column_totals[3]4cat(last_total, "\n", sep = "")output11values this step11last_total
Follow the Matrix
matrix(1:6, nrow = 2)creates 2 rows and 3 columns.- R fills the matrix by columns.
- The column sums are
1 + 2,3 + 4, and5 + 6. column_totalsbecomes3,7, and11.column_totals[3]is11, so the script prints11. | column | values | total | | --- | --- | --- | | 1 | 1, 2 | 3 | | 2 | 3, 4 | 7 | | 3 | 5, 6 | 11 |
matrix
`matrix(1:6, nrow = 2)` creates a rectangular numeric structure.
colSums
`colSums` adds values down each column.
dimension
Matrices keep row and column shape in `dim`.
Exercise: matrices.R
Reproduce the printed value 11, then change one value in 1:6 and predict the affected column total before running it.