The Analogy: The Grading Shed's Slotted Tray and Stamp Set
The grading shed at the far end of the packhouse works with slotted trays: a shallow wooden frame divided into a fixed grid of pockets, and the shed's standing order is that a tray is filled one column at a time. The packer stands at the short end, drops fruit into the pocket nearest to them, works down that column to the far side, then steps along and starts the next column. Nobody chose this for elegant reasons; it is simply where the packer's arm reaches. The consequence matters later: the sequence in which fruit entered the tray runs down the columns, not across the rows, so a clerk who reads the tray left-to-right along a row is reading the pockets in an order that never happened.
The tray's shape is chalked on the end board -- 4 by 5 -- and that chalk is the only thing that makes the frame a grid. Prise out the dividers and you have twenty pockets in a single line, in exactly the order the packer filled them. The grid is a way of reading the contents, not a property of the fruit. The one-commodity rule from the main line still applies unchanged: a tray of apples with one pear in it is a tray of mixed fruit, and mixed fruit has no grade.
Grades themselves are not written out in words. The shed has a stamp set, one numbered die per grade, and a legend card nailed above the bench: 1 is SMALL, 2 is MEDIUM, 3 is LARGE. Every docket that leaves the shed carries a number, and the words exist only on the card. This is deliberate and it pays for itself twice. A number is faster to stamp than a word, and the end-of-shift tally becomes a count of three stamp values rather than a sift through free text where three clerks have written Med, MEDIUM and medium on three different dockets.
Two things go wrong, and the second is worse than it looks. A fruit that matches no grade on the card -- a jumbo the card never anticipated -- gets no stamp at all, and a blank docket is not treated as a complaint. It flows on and appears in the tally as an absence rather than a problem, so the counts still look tidy while quietly summing to fewer dockets than the shed actually processed. The second failure is the legend card itself. Reprint it with the grades in a different order and every docket already stamped now reads a different grade, because the docket only ever held a number. Nothing physical changed, no record was altered, and a year of history shifted by one.
Syntax or Core Structure
A matrix is not a new kind of container. It is an ordinary atomic vector with a dim attribute stuck to it, and the attribute is what makes indexing by row and column legal. A factor is also an ordinary integer vector with two attributes: levels, which is the lookup table of labels, and class, which tells R to print the labels instead of the codes.
# --- A matrix is filled down its columns unless you say otherwise ---
m <- matrix(1:6, nrow = 2, ncol = 3)
print(m)
cat(sprintf("dim(m) : %s\n", paste(dim(m), collapse = " x ")))
cat(sprintf("length(m) : %d\n", length(m)))
cat(sprintf("m[2, 3] : %d\n", m[2, 3]))
cat(sprintf("m[4] : %d (one linear index, counted down the columns)\n", m[4]))
# --- Remove the dim attribute and the grid disappears ---
flat <- m
dim(flat) <- NULL
cat(sprintf("flattened : %s\n", paste(flat, collapse = " ")))
# --- A factor is codes plus a legend ---
sizes <- c("Medium", "Small", "Large", "Medium", "Large")
size_f <- factor(sizes, levels = c("Small", "Medium", "Large"), ordered = TRUE)
cat(sprintf("levels : %s\n", paste(levels(size_f), collapse = " < ")))
cat(sprintf("codes : %s\n", paste(as.integer(size_f), collapse = " ")))
cat(sprintf("labels : %s\n", paste(as.character(size_f), collapse = " ")))
cat(sprintf("Large > Medium ? %s\n", size_f[3] > size_f[1]))
# --- The tally is a count of codes, printed one line at a time ---
tally <- table(size_f)
cat(sprintf("%-8s %5s\n", "GRADE", "COUNT"))
for (g in levels(size_f)) {
cat(sprintf("%-8s %5d\n", g, tally[[g]]))
}
Output:
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
dim(m) : 2 x 3
length(m) : 6
m[2, 3] : 6
m[4] : 4 (one linear index, counted down the columns)
flattened : 1 2 3 4 5 6
levels : Small < Medium < Large
codes : 2 1 3 2 3
labels : Medium Small Large Medium Large
Large > Medium ? TRUE
GRADE COUNT
Small 1
Medium 2
Large 2
Technical Depth: Attributes, Storage Order, and Level Discipline
The attributes that do the work
Almost everything R calls a data structure is a vector with attributes attached. Understanding which attribute is doing what removes most of the mystery, because setting or clearing one changes the type of thing you are holding without moving a single value.
| Attribute | What it holds | How you set it | What clearing it does |
|---|---|---|---|
| dim | an integer vector of extents | dim(x) is assigned c(2L, 3L) | the value collapses back to a plain vector |
| dimnames | a list of one character vector per axis | dimnames(x) is assigned a list | indexing and printing by name stop working |
| names | one label per element | names(x) is assigned a character vector | positional indexing still works, by-name does not |
| levels | the label lookup table of a factor | levels(f) is assigned a character vector | the factor prints as bare integer codes |
| class | the S3 class label used for dispatch | class(x) is assigned a string | printing falls back to the implicit class |
Storage is column-major, and byrow only changes the filling
The byrow = TRUE argument is a convenience for writing a literal that reads the way the data looks on paper. It does not change how R stores the values. Storage is always column-major, so flattening a byrow matrix gives you an order that matches neither the literal you typed nor the rows you see.
by_col <- matrix(1:6, nrow = 2)
by_row <- matrix(1:6, nrow = 2, byrow = TRUE)
cat(sprintf("by_col row 1 : %s\n", paste(by_col[1, ], collapse = " ")))
cat(sprintf("by_row row 1 : %s\n", paste(by_row[1, ], collapse = " ")))
cat(sprintf("by_col flattened : %s\n", paste(as.vector(by_col), collapse = " ")))
cat(sprintf("by_row flattened : %s\n", paste(as.vector(by_row), collapse = " ")))
Output:
by_col row 1 : 1 3 5
by_row row 1 : 1 2 3
by_col flattened : 1 2 3 4 5 6
by_row flattened : 1 4 2 5 3 6
That last line is the one that ruins a CSV export. Code that builds a matrix with byrow = TRUE for readability and then writes as.vector(m) to a file produces a stream in shelf-major order while the header says otherwise, and nothing errors.
Two multiplications that both compile
The star operator is elementwise and the percent-star-percent operator is linear algebra. Both accept two conformable matrices, both return a matrix, and neither warns you that you meant the other one. On square inputs of the same size they even return the same shape, which is why this bug survives review.
a <- matrix(1:4, nrow = 2)
b <- matrix(5:8, nrow = 2)
cat(sprintf("elementwise : %s\n", paste(as.vector(a * b), collapse = " ")))
cat(sprintf("matrix mult : %s\n", paste(as.vector(a %*% b), collapse = " ")))
cat(sprintf("mult dim : %s\n", paste(dim(a %*% b), collapse = " x ")))
print(a %*% b)
Output:
elementwise : 5 12 21 32
matrix mult : 23 34 31 46
mult dim : 2 x 2
[,1] [,2]
[1,] 23 31
[2,] 34 46
The flattened product reads 23 34 31 46 while the printed matrix reads across as 23 31 then 34 46. Same object, two orders, because as.vector walks down the columns.
Level discipline: three ways a factor loses data
A factor is only as good as its legend. Every value that is not in levels becomes NA at construction time, silently, and table() then omits it from the tally.
raw <- c("Medium", "Jumbo", "Small")
grade <- factor(raw, levels = c("Small", "Medium", "Large"))
tally <- table(grade)
cat(sprintf("codes : %s\n", paste(as.integer(grade), collapse = " ")))
cat(sprintf("length : %d\n", length(grade)))
cat(sprintf("tally sum : %d\n", sum(tally)))
cat(sprintf("any NA : %s\n", any(is.na(grade))))
Output:
codes : 2 NA 1
length : 3
tally sum : 2
any NA : TRUE
Three readings went in and the tally accounts for two. Nothing was printed at construction time to tell you that Jumbo was not on the legend card.
The second trap is a factor built from numbers that arrived as text. The levels get sorted as strings, and as.integer returns the position in that sorted legend rather than the number you can see.
years <- factor(c("1998", "2007", "1985"))
cat(sprintf("levels : %s\n", paste(levels(years), collapse = " ")))
cat(sprintf("as.integer : %s\n", paste(as.integer(years), collapse = " ")))
cat(sprintf("via char : %s\n", paste(as.integer(as.character(years)), collapse = " ")))
Output:
levels : 1985 1998 2007
as.integer : 2 3 1
via char : 1998 2007 1985
The third trap is reordering. Re-declaring the levels renumbers every code in place while the labels stay exactly the same, so a saved column of codes from last month means something different today.
g <- factor(c("Small", "Large", "Medium"), levels = c("Small", "Medium", "Large"))
g2 <- factor(g, levels = c("Large", "Medium", "Small"))
cat(sprintf("before : %s\n", paste(as.integer(g), collapse = " ")))
cat(sprintf("after : %s\n", paste(as.integer(g2), collapse = " ")))
cat(sprintf("labels : %s\n", paste(as.character(g2), collapse = " ")))
Output:
before : 1 3 2
after : 3 1 2
labels : Small Large Medium
Store the labels, not the codes. The codes are only meaningful next to the exact legend that produced them.
Real World Example: A Drying-Shed Moisture Log
A timber drying shed holds four shelves of boards. A technician walks the shed once a day for five days and writes the moisture percentage of each shelf on a clipboard. At the end of the week the shed supervisor wants one sheet: the raw grid, how far each shelf fell over the week, each shelf's average, each day's average across the shed, and a grade telling whether the shelf dried too slowly, correctly, or too fast. The whole job is a matrix with two margins summarised and a factor produced by banding one of those margins.
readings <- matrix(
c(62L, 58L, 55L, 51L, 48L,
60L, 57L, 54L, 52L, 50L,
64L, 63L, 61L, 60L, 59L,
59L, 54L, 49L, 45L, 41L),
nrow = 4, byrow = TRUE,
dimnames = list(c("A", "B", "C", "D"),
c("D1", "D2", "D3", "D4", "D5"))
)
shelf_id <- rownames(readings)
day_id <- colnames(readings)
drop_pts <- readings[, 1] - readings[, 5]
shelf_mean <- rowMeans(readings)
day_mean <- colMeans(readings)
grade <- cut(drop_pts,
breaks = c(0L, 8L, 15L, 100L),
labels = c("UNDER", "ON", "OVER"))
hdr_fmt <- "%-6s%6s%6s%6s%6s%6s%7s%8s%7s\n"
row_fmt <- "%-6s%6d%6d%6d%6d%6d%7d%8.2f%7s\n"
avg_fmt <- "%-6s%6.2f%6.2f%6.2f%6.2f%6.2f\n"
rule <- strrep("-", 58)
cat(sprintf(hdr_fmt, "SHELF", day_id[1], day_id[2], day_id[3],
day_id[4], day_id[5], "DROP", "MEAN", "GRADE"))
cat(rule, "\n", sep = "")
for (i in seq_along(shelf_id)) {
cat(sprintf(row_fmt, shelf_id[i],
readings[i, 1], readings[i, 2], readings[i, 3],
readings[i, 4], readings[i, 5],
drop_pts[i], shelf_mean[i], as.character(grade[i])))
}
cat(rule, "\n", sep = "")
cat(sprintf(avg_fmt, "MEAN", day_mean[1], day_mean[2], day_mean[3],
day_mean[4], day_mean[5]))
tally <- table(grade)
cat("\n")
cat(sprintf("%-7s%5s\n", "GRADE", "COUNT"))
for (g in levels(grade)) {
cat(sprintf("%-7s%5d\n", g, tally[[g]]))
}
Output:
SHELF D1 D2 D3 D4 D5 DROP MEAN GRADE
----------------------------------------------------------
A 62 58 55 51 48 14 54.80 ON
B 60 57 54 52 50 10 54.60 ON
C 64 63 61 60 59 5 61.40 UNDER
D 59 54 49 45 41 18 49.60 OVER
----------------------------------------------------------
MEAN 61.25 58.00 54.75 52.00 49.50
GRADE COUNT
UNDER 1
ON 2
OVER 1
Read the structure rather than the numbers. There is exactly one data object, readings, and everything else is a derived margin. readings[, 1] and readings[, 5] each drop the dim attribute and come back as plain named vectors of length four, which is why drop_pts subtracts cleanly. rowMeans and colMeans are the two margins, and they return vectors of different lengths -- four and five -- so they can never be accidentally combined without R complaining about recycling. The dimnames list carries the labels, and rownames and colnames pull them back out for the header and the row stubs, so the printed sheet and the stored object cannot drift apart.
The grade column is the only place a factor appears, and it is doing real work. cut takes the four drop values, decides which band each falls in, and returns a factor whose levels are already in the meaningful order UNDER, ON, OVER rather than alphabetical. That ordering is why the tally at the bottom reads in inspection order: levels(grade) drives the loop, so the counts come out in band order without a sort. If the grades had been built as plain strings and counted with table, the tally would have read ON, OVER, UNDER, which is alphabetical and useless to a supervisor reading down a page.
Notice also what the report does not do. It never prints the factor object, only as.character(grade[i]), and it never prints tally directly. Both of those are deliberate. R pads factor and table output to the width of the widest label, which puts trailing spaces on short rows and makes the file impossible to diff cleanly. Passing the label through sprintf with an explicit width gives the same alignment under your own control.
The design flaw is in the breaks argument. cut is right-closed by default, so the bands are the half-open intervals from just above 0 up to 8, from just above 8 up to 15, and from just above 15 up to 100. A shelf that did not dry at all has a drop of exactly 0, which falls in no band and becomes NA. That shelf then prints the literal text NA in the GRADE column, and -- worse -- table() omits NA by default, so the tally at the bottom would sum to three while the sheet above it shows four shelves. A completely dead shelf, the single most urgent thing in the shed, is the one case the report cannot grade and quietly drops from the summary. Fixing it means either breaks = c(-1L, 8L, 15L, 100L) or include.lowest = TRUE, plus table(grade, useNA = "ifany") so a future NA is loud instead of invisible. Two smaller faults sit alongside it: the five day columns are hard-coded into three format strings, so a six-day week silently truncates the sheet to five columns, and the upper break of 100 is an unstated assumption that no drop ever exceeds one hundred points, which would send an implausible sensor reading to NA down the same silent path.
Common Mistakes
- Forgetting
byrow = TRUEwhen the literal reads in rows. Typing the drying-shed grid one shelf per line and omittingbyrowgives a matrix with the right dimensions and every value in the wrong cell. Nothing errors, because a 4-by-5 matrix built column-major from twenty numbers is a perfectly valid 4-by-5 matrix. The only symptom is that shelf A's week now contains one reading from each of four different shelves.
- Assuming
byrow = TRUEchanged how the values are stored. It changed only the order they were consumed during construction. Storage stays column-major forever, soas.vectoron abyrowmatrix returns neither the order you typed nor the order you see. Anything that flattens for export --as.vector,c(),writeLinesover a coerced vector -- has to transpose first or walk the rows explicitly.
- Writing
*when you meant%*%. On two square matrices of the same size both operators succeed and both return a matrix of that same size, so the shape check that would normally catch the slip does not fire. The elementwise result5 12 21 32and the matrix product23 34 31 46are both plausible-looking numbers. Only the arithmetic tells them apart.
- Losing the
dimattribute on a single-row or single-column extraction.readings[1, ]returns a length-5 vector, not a 1-by-5 matrix, becausedrop = TRUEis the default. Code that then callsnrowon it getsNULL, andNULLin an arithmetic comparison produces a zero-length logical, which in anifraises an error about needing a length-one condition. The fix isreadings[1, , drop = FALSE].
- Calling
as.integeron a factor of numeric-looking strings.as.integer(factor(c("1998", "2007", "1985")))returns2 3 1-- the positions in the sorted legend -- not the years. The result is small, positive, plausible integers, which is exactly why it gets written to a database column and discovered a quarter later. Alwaysas.integer(as.character(f)).
- Letting the default alphabetical sort decide the level order.
factor(c("Small", "Medium", "Large"))produces levels in the order Large, Medium, Small, so every tally, every axis, and every ordered comparison runs backwards from what the domain means. Declarelevelsyourself whenever the categories have a natural order.
- Values outside
levelsbecomingNAin silence. A reading of"Jumbo"against levels Small, Medium, Large is not an error and not a warning; it is anNA.table()then omits it by default, so the tally under-counts and the shortfall is invisible unless you compare the tally's sum againstlength().
- Reordering levels and continuing to trust stored integer codes. Re-declaring the levels renumbers every code in place while every label stays the same, so last month's exported codes and this month's legend disagree with no version marker to warn you. Codes are only meaningful next to the exact legend that produced them.
- Binding a text column onto a numeric matrix. A matrix is one atomic vector, so
cbind(readings, grade_labels)coerces every number to character to accommodate the strings. The result still prints as a neat grid, butrowMeanson it now fails, and comparisons likem[, 1] > 60start comparing strings, where"9"is greater than"60". When rows must mix types, the structure you need is a data frame, not a matrix.
Best Practices
- Give every matrix its
dimnamesat construction time and read the labels back withrownamesandcolnamesrather than keeping a parallel vector of headings. One object then carries both the numbers and their meaning, and a printed sheet cannot drift away from the data it claims to describe.
- State
byrowexplicitly on everymatrixcall, even when the default is what you want, so the next reader never has to work out which way twenty numbers were consumed. Then never flatten for export withas.vector-- transpose witht()first, or emit one row at a time.
- Pass
drop = FALSEon any extraction whose result is handed to code that expects a matrix. A function that works on a five-shelf shed and breaks on a one-shelf shed is almost always a missingdrop = FALSE.
- Reach for
rowMeans,colMeans,rowSums,colSums, orapplywith an explicitMARGINinstead of writing an index loop over a matrix. The margin function names the axis you meant, so a transposed input produces a length mismatch instead of a quietly wrong average.
- Declare
levelsyourself whenever the categories have an order that matters, and list them in the order a human would inspect them. Everything downstream -- tallies, ordered comparisons, plot axes, report rows -- inherits that order for free.
- Assert that the tally accounts for every row: check that
sum(table(x, useNA = "ifany"))equalslength(x)right after you build a factor. This single line catches unmapped labels, out-of-bandcutvalues, and left-open interval bugs in one go.
- Store labels, not codes, in anything that outlives the session. If you genuinely need the numbers behind a numeric-looking factor, go through
as.characterfirst and never throughas.integeralone.
- Format report lines with
sprintfand explicit field widths rather than printing a factor or a table object directly. R pads those to the widest label, which puts trailing spaces on short rows; explicit widths give you the same alignment plus a file that diffs cleanly.
Practice Exercises
- Rebuild the drying-shed report and add a fifth shelf, E, whose five readings are all
57Lso its drop is exactly zero. Run the report unchanged and confirm two things: the GRADE column printsNAfor shelf E, and the tally at the bottom sums to four while the grid above shows five shelves. Then fix it two ways -- once withinclude.lowest = TRUEand once by moving the first break below zero -- and add a line that stops the program whensum(table(grade, useNA = "ifany"))does not equallength(grade).
- Write
in_reading_order(m)that returns a plain vector of a matrix's values in the order they appear on screen, left to right then top to bottom. Verify it on bothmatrix(1:6, nrow = 2)andmatrix(1:6, nrow = 2, byrow = TRUE), printingas.vector(m)alongside your result so the difference between storage order and reading order is visible in the same output block. Then state in a comment which of the two matrices makesas.vectora correct export and why.
- Take the moisture grid and write a function that returns, for one named shelf, a 1-by-5 matrix rather than a length-5 vector -- so that
dimon the result is1 5andrownamesstill carries the shelf letter. Then write a second version withoutdrop = FALSEand printdim,nrow, andclassfor both results side by side to show exactly what the default extraction throws away.
- Build a factor of the six shelf grades
c("ON", "OVER", "ON", "UNDER", "ON", "OVER")with levels declared in inspection order, and save its integer codes to a variable as if writing them to a file. Now re-declare the levels in alphabetical order, decode the saved codes against the new legend, and print the original labels next to the decoded ones. Count how many of the six now read as the wrong grade, then rewrite the save step so that it survives a level reordering.