R / CHAPTER 06
Matrix shape and margin operations
IntermediateAlign row and column operations explicitly.
By the end of this chapter
- Predict column-major construction
- Distinguish elementwise and matrix multiplication
- Apply summaries along the intended margin
The idea
A matrix is an atomic vector with a two-dimensional shape. R fills matrix data by columns unless byrow is requested, so inspect a small example before assuming the input sequence represents rows. Row and column indices are separate dimensions. Keep dimensions when a downstream function expects a matrix, especially when selecting a single column.
The star operator multiplies corresponding elements, while percent-star-percent performs matrix multiplication with compatible inner dimensions. To subtract each column mean, use sweep with margin two instead of relying on accidental recycling. State the intended dimensions of every intermediate result. Test rectangular matrices as well as square ones, because a square example can conceal a mistaken row-versus-column assumption.
m <- matrix(1:6,nrow=2)
centered <- sweep(m,2,colMeans(m),"-")
cat(m[2,3], "\n", sep="")
cat(colSums(centered), sep=",")
cat("\n")6 0,0,0
Columns are (1,2), (3,4), and (5,6). Subtracting each column mean leaves every column sum at zero.
Try it yourself
Center every row of a rectangular matrix using its row mean.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING