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 = "")
  1. grid ← 2 x 3 matrix

    1grid <- matrix(1:6, nrow = 2)2column_totals <- colSums(grid)
    values this step2 x 3 matrixgrid
  2. column_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 columns
  3. last_total ← 11

    2column_totals <- colSums(grid)3last_total <- column_totals[3]4cat(last_total, "\n", sep = "")
    values this step11last_total11column_totals[3]
  4. cat(last_total, " ", sep = "")

    3last_total <- column_totals[3]4cat(last_total, "\n", sep = "")
    output11
    values this step11last_total

Follow the Matrix

  1. matrix(1:6, nrow = 2) creates 2 rows and 3 columns.
  2. R fills the matrix by columns.
  3. The column sums are 1 + 2, 3 + 4, and 5 + 6.
  4. column_totals becomes 3, 7, and 11.
  5. column_totals[3] is 11, so the script prints 11. | 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.