Data Frames

Data Frames in R: --- Above the tally clerk's desk in a census office runs a long brass rail, and clipped to it hang a dozen paper strips.


The Analogy: The Census Office's Rail of Column Strips

Above the tally clerk's desk in a census office runs a long brass rail, and clipped to it hang a dozen paper strips. Each strip carries the answers to one question for the whole district, written top to bottom in a single hand: house numbers in ink on the first strip, occupancy counts in pencil on the second, a strip of ticks and crosses for whether the form came back, a strip of one-word ward names. Every mark on a strip is the same kind of mark as every other mark on that strip -- you would never find a ward name halfway down the occupancy strip -- but the strips themselves are as different from each other as a number is from a tick. And every strip is cut to exactly the same length, one line per household, because that is the only thing holding the whole arrangement together.

A household is not an object on that rail. There is no card, no envelope, no folder for household fourteen. Household fourteen means the fourteenth line on every strip, read across at one height, and nothing physically fastens the fourteenth house number to the fourteenth occupancy count except that they happen to hang level with each other. When the clerk needs to read a household out loud, they lay a steel ruler across the rail and read what the ruler touches. The row is a sightline, not a thing.

There are two ways to take material off the rail, and they mirror the two ways of taking things out of a pocketed folder. Unclip a single strip and carry it to the desk: you now hold one strip, all one kind of mark, and you can total it or sort it or count its ticks. Or unfasten a short section of rail with several strips still hanging from it: you now hold a smaller rail, and the ruler still works. The office also permits clipping up a strip shorter than the rail, in which case the clerk simply repeats it down the length to fill. A single strip reading EARLY, repeated for every household, is a genuine convenience. A strip of two marks repeated ten times to fill a rail of twenty is a catastrophe wearing exactly the same clothes.

The failures follow from the row being a sightline. The one that ends careers is unclipping the occupancy strip, sorting it into ascending order because somebody wanted to see the range, and clipping it back on the rail. Nothing looks wrong afterwards. Every strip is still the correct length, still in the correct hand, still hanging level. But the ruler now reads house number 12 against an occupancy that belongs to house number 40, and every household on the rail is a stranger's answers under somebody else's address, with no mark anywhere to say so. The second failure is the short strip: a strip whose length divides the rail's length evenly is repeated without comment, while one that does not divide is rejected at the counter, so the case that gets caught is the harmless one and the case that gets through is the one that quietly duplicates data. And the third is asking for a section of rail that happens to hold exactly one strip, and being handed the bare strip instead -- at which point the ruler you were about to lay across it has nothing left to rest on.


Syntax or Core Structure

data.frame takes one named argument per column, each a vector, and requires them all to be the same length -- or a length that divides it. What you get back is a list of those vectors with a class attribute and a set of row names, which is why every list accessor from the previous lesson still works.

patients <- data.frame(
  id     = 1:4,
  name   = c("Alice", "Bob", "Charlie", "David"),
  age    = c(45L, 32L, 58L, 29L),
  healed = c(TRUE, FALSE, TRUE, TRUE)
)

cat(sprintf("dim        : %s\n", paste(dim(patients), collapse = " x ")))
cat(sprintf("nrow, ncol : %d, %d\n", nrow(patients), ncol(patients)))
cat(sprintf("names      : %s\n", paste(names(patients), collapse = " ")))
cat(sprintf("col types  : %s\n", paste(sapply(patients, class), collapse = " ")))
cat(sprintf("mean age   : %.2f\n", mean(patients$age)))
cat(sprintf("one column : %s\n", class(patients[["age"]])))
cat(sprintf("one strip  : %s\n", class(patients["age"])))
cat(sprintf("row 3 name : %s\n", patients[3, "name"]))
cat(sprintf("healed n   : %d\n", sum(patients$healed)))
print(patients[patients$age > 30, c("name", "healed")])

Output:

dim        : 4 x 4
nrow, ncol : 4, 4
names      : id name age healed
col types  : integer character integer logical
mean age   : 41.00
one column : integer
one strip  : data.frame
row 3 name : Charlie
healed n   : 3
     name healed
1   Alice   TRUE
2     Bob  FALSE
3 Charlie   TRUE

Four things in that output are worth pausing on. col types shows four columns of three different classes coexisting, which no matrix can do. one column against one strip is the list lesson again: double brackets unclip the strip and hand you an integer vector, single brackets hand you a one-column data frame. sum(patients$healed) counts TRUE values because a logical vector sums as ones and zeros. And the printed subset keeps its original row names -- 1, 2, 3 here -- rather than renumbering, which becomes important the moment the rows are reordered.

Note that print on a data frame right-aligns every column, including character ones, so its output has no trailing whitespace. That is not true of printing a factor or a table, which pad to the widest label.


Technical Depth: Indexing, Recycling, and the Row as a Sightline

Seven ways to index, and what each hands back

The single most common source of confusion with data frames is that the same bracket does different things depending on how many arguments you give it and how many columns come back.

ExpressionReturnsNote
df$agethe column as a vectorpartial matching applies
df[["age"]]the column as a vectorexact by default
df["age"]a one-column data framethe strip stays clipped to the rail
df[, "age"]a vector, because drop defaults to TRUEshape depends on how many columns you asked for
df[, "age", drop = FALSE]a one-column data frameshape is stated rather than inferred
df[2, ]a one-row data framerows never simplify to a vector
df[df$age > 30, ]the matching rows, row names kepta logical vector selects rows

The fourth row is the one that breaks functions. A helper written and tested against a three-column selection works perfectly until somebody calls it with one column, at which point the comma form hands back a bare vector and every subsequent nrow returns NULL.

patients <- data.frame(id = 1:4, age = c(45L, 32L, 58L, 29L))

one_col <- patients[, "age"]
kept    <- patients[, "age", drop = FALSE]
one_row <- patients[2, ]

cat(sprintf("one_col class : %s\n", class(one_col)))
cat(sprintf("one_col dim   : %s\n", is.null(dim(one_col))))
cat(sprintf("kept class    : %s\n", class(kept)))
cat(sprintf("kept dim      : %s\n", paste(dim(kept), collapse = " x ")))
cat(sprintf("one_row class : %s\n", class(one_row)))
cat(sprintf("one_row dim   : %s\n", paste(dim(one_row), collapse = " x ")))
cat(sprintf("two cols dim  : %s\n", paste(dim(patients[, c("id", "age")]), collapse = " x ")))

Output:

one_col class : integer
one_col dim   : TRUE
kept class    : data.frame
kept dim      : 4 x 1
one_row class : data.frame
one_row dim   : 1 x 2
two cols dim  : 4 x 2

one_col dim : TRUE is reporting that dim returned NULL: the object has no dimensions at all any more. Selecting two columns keeps the data frame, selecting one does not, and the only thing that made the difference was the data. Writing drop = FALSE costs thirteen characters and removes that dependency permanently.

Recycling on construction: silent when it divides, loud when it does not

data.frame will stretch a short column to the length of the longest one, but only if the short length divides the long one exactly. A length-1 column becomes a constant, which is genuinely useful. A length-2 column silently becomes an alternating pattern, which almost never is.

grid <- data.frame(
  zone  = c("N", "S", "E", "W"),
  shift = "EARLY",
  flag  = c(TRUE, FALSE),
  stringsAsFactors = FALSE
)

cat(sprintf("dim   : %s\n", paste(dim(grid), collapse = " x ")))
cat(sprintf("shift : %s\n", paste(grid$shift, collapse = " ")))
cat(sprintf("flag  : %s\n", paste(grid$flag, collapse = " ")))

bad <- try(data.frame(zone = c("N", "S", "E", "W"), pair = c(1L, 2L, 3L)),
           silent = TRUE)
cat(sprintf("errored : %s\n", inherits(bad, "try-error")))

Output:

dim   : 4 x 3
shift : EARLY EARLY EARLY EARLY
flag  : TRUE FALSE TRUE FALSE
errored : TRUE

The flag column was never meant to alternate. Three values against four rows raises arguments imply differing number of rows, so the mistake that cannot be repaired is reported and the mistake that can be repaired is not. try with silent = TRUE catches the condition and inherits(bad, "try-error") tests for it, which keeps the error text off stdout instead of interleaving it with the report.

Sorting one strip unclips it from the rail

A row is a sightline across the rail, not an object. Nothing binds kg to bin except position, so assigning a sorted vector back into a single column reorders that column alone and every row silently becomes a different, wrong pairing.

bins <- data.frame(
  bin = c("B1", "B2", "B3", "B4"),
  kg  = c(12L, 41L, 7L, 33L),
  stringsAsFactors = FALSE
)

show <- function(label, d) {
  cat(sprintf("%-13s: %s\n", label,
              paste(sprintf("%s=%d", d$bin, d$kg), collapse = " ")))
}
kg_for <- function(d, b) d$kg[d$bin == b]

wrong <- bins
wrong$kg <- sort(bins$kg)
right <- bins[order(bins$kg), ]

show("orig bin/kg", bins)
show("wrong bin/kg", wrong)
show("right bin/kg", right)
cat(sprintf("%-13s: %s\n", "row names", paste(rownames(right), collapse = " ")))
cat(sprintf("%-13s: %d\n", "torn kg orig", kg_for(bins, "B3")))
cat(sprintf("%-13s: %d\n", "torn kg wrong", kg_for(wrong, "B3")))
cat(sprintf("%-13s: %d\n", "torn kg right", kg_for(right, "B3")))

Output:

orig bin/kg  : B1=12 B2=41 B3=7 B4=33
wrong bin/kg : B1=7 B2=12 B3=33 B4=41
right bin/kg : B3=7 B1=12 B4=33 B2=41
row names    : 3 1 4 2
torn kg orig : 7
torn kg wrong: 33
torn kg right: 7

Bin B3 held 7 kg before the sort and reads 33 kg after it. The right version reorders the whole rail with a row index built by order, so every strip moves together and B3 still reads 7 kg. The leftover row names 3 1 4 2 are the tell: they record where each row came from, which is why right["3", ] and right[3, ] are now different rows. Call rownames(right) <- NULL after any reordering unless you specifically want that history.


Real World Example: A Goods-Inwards Reconciliation

A stores office receives delivery lines against purchase orders. Each line names a part, a supplier, a quantity ordered and a quantity actually counted onto the shelf. Unit prices live in a separate reference table, because prices change on a different schedule from deliveries and nobody wants to retype them on every line. The job is to join the two, work out shortfalls, value what arrived, and print a sheet the buyer can sign.

lines <- data.frame(
  ref      = c("L-01", "L-02", "L-03", "L-04", "L-05"),
  part     = c("BOLT", "NUT", "WASHER", "BOLT", "PLATE"),
  supplier = c("ACME", "ACME", "BRIX", "BRIX", "ACME"),
  ordered  = c(200L, 500L, 500L, 120L, 40L),
  received = c(200L, 480L, 500L, 0L, 44L),
  stringsAsFactors = FALSE
)

prices <- data.frame(
  part = c("BOLT", "NUT", "WASHER", "PLATE"),
  unit = c(0.42, 0.09, 0.05, 3.75),
  stringsAsFactors = FALSE
)

lines <- merge(lines, prices, by = "part")
merged_names <- names(lines)
lines <- lines[order(lines$ref), ]

lines$short  <- lines$ordered - lines$received
lines$value  <- lines$received * lines$unit
lines$status <- ifelse(lines$received == 0L, "NIL",
                ifelse(lines$short > 0L, "SHORT",
                ifelse(lines$short < 0L, "OVER", "OK")))

hdr  <- "%-6s%-8s%-6s%6s%6s%7s%7s%9s%8s\n"
row  <- "%-6s%-8s%-6s%6d%6d%7d%7.2f%9.2f%8s\n"
tot  <- "%-20s%6d%6d%7d%7s%9.2f\n"
rule <- strrep("-", 63)

cat(sprintf(hdr, "REF", "PART", "SUPP", "ORD", "RECD", "SHORT",
            "UNIT", "VALUE", "STATUS"))
cat(rule, "\n", sep = "")
for (i in seq_len(nrow(lines))) {
  cat(sprintf(row, lines$ref[i], lines$part[i], lines$supplier[i],
              lines$ordered[i], lines$received[i], lines$short[i],
              lines$unit[i], lines$value[i], lines$status[i]))
}
cat(rule, "\n", sep = "")
cat(sprintf(tot, "TOTAL", sum(lines$ordered), sum(lines$received),
            sum(lines$short), "", sum(lines$value)))

sup <- aggregate(cbind(received, value) ~ supplier, data = lines, FUN = sum)
cat("\n")
cat(sprintf("%-10s%8s%10s\n", "SUPPLIER", "RECD", "VALUE"))
for (i in seq_len(nrow(sup))) {
  cat(sprintf("%-10s%8d%10.2f\n", sup$supplier[i], sup$received[i], sup$value[i]))
}

cat("\n")
cat(sprintf("%-17s : %s\n", "names after merge", paste(merged_names, collapse = " ")))
cat(sprintf("%-17s : %s\n", "nil lines",
            paste(lines$ref[lines$status == "NIL"], collapse = ", ")))
cat(sprintf("%-17s : %s\n", "short or nil",
            paste(lines$ref[lines$status %in% c("SHORT", "NIL")], collapse = ", ")))
cat(sprintf("%-17s : %s\n", "value reconciles",
            isTRUE(all.equal(sum(lines$value), sum(sup$value)))))

Output:

REF   PART    SUPP     ORD  RECD  SHORT   UNIT    VALUE  STATUS
---------------------------------------------------------------
L-01  BOLT    ACME     200   200      0   0.42    84.00      OK
L-02  NUT     ACME     500   480     20   0.09    43.20   SHORT
L-03  WASHER  BRIX     500   500      0   0.05    25.00      OK
L-04  BOLT    BRIX     120     0    120   0.42     0.00     NIL
L-05  PLATE   ACME      40    44     -4   3.75   165.00    OVER
---------------------------------------------------------------
TOTAL                 1360  1224    136          317.20

SUPPLIER      RECD     VALUE
ACME           724    292.20
BRIX           500     25.00

names after merge : part ref supplier ordered received unit
nil lines         : L-04
short or nil      : L-02, L-04
value reconciles  : TRUE

The program never touches a row as an object. merge matches the two rails on part and hands back a new rail whose strips are aligned by construction, and the names after merge line records the first surprise: the join column is moved to the front, so the column order you wrote is not the column order you get. Anything downstream that indexed by position rather than by name is now reading the wrong strip. merge also returns its rows grouped by the join key rather than in input order, which is why the explicit lines[order(lines$ref), ] is there: without it the sheet would print BOLT, BOLT, NUT, PLATE, WASHER and the buyer's line references would appear shuffled.

The three derived columns are ordinary vectors clipped onto the same rail. lines$short subtracts two integer strips elementwise, lines$value multiplies an integer strip by a double strip and produces a double, and lines$status is a nested ifelse evaluated across all five rows at once. None of this loops. The only loops in the program are the two that print, and they exist because printing is inherently row-at-a-time; the arithmetic above them is column-at-a-time and would run the same way on fifty thousand lines.

aggregate(cbind(received, value) ~ supplier, ...) reads as a sentence: summarise received and value, broken down by supplier. It returns a data frame with one row per group, its groups in sorted order, which is what makes the second block reproducible without an explicit sort. The final check compares the line-level total against the supplier-level total through all.equal rather than ==, because both sides are doubles accumulated in different orders and exact equality on floating point is a coin toss; isTRUE collapses all.equal's "mean relative difference" message down to a plain FALSE so the line always prints a logical.

The limits are worth stating plainly. The most serious is the join itself: merge defaults to all = FALSE, an inner join. If a delivery line names a part that is absent from prices -- a new part number, a typo, a trailing space -- that line is dropped without a warning, and because every total on the sheet is computed after the merge, the sheet still reconciles perfectly. A signed-off document that silently omits stock is worse than one that fails, and the fix is all.x = TRUE plus an explicit sum(is.na(lines$unit)) check before printing. Second, value <- received * unit is uncapped, so L-05's over-delivery of four plates is valued at its full 165.00 and the 317.20 total is the value of what arrived rather than the value of what was ordered; a stores system that pays on that figure pays for goods nobody requisitioned. Third, status is a character vector, so it cannot be tallied in a meaningful order and ifelse evaluates every branch for every row regardless of which one is selected; an ordered factor with levels NIL, SHORT, OK, OVER would fix both. Fourth, the reordering leaves the merge's row names behind, so lines["3", ] and lines[3, ] are now different lines, and only one of them is the one a reader means.


Common Mistakes

  1. Assuming a single-column selection is still a data frame. df[, "age"] drops to a vector, df[, c("id", "age")] does not. A function that works on two columns and breaks on one has this bug, and drop = FALSE is the whole fix.
  1. Sorting one column in place. df$kg <- sort(df$kg) reorders that strip alone and silently re-pairs every row. Reorder the frame with a row index instead: df <- df[order(df$kg), ].
  1. Forgetting that merge is an inner join by default. Unmatched rows disappear and no warning is issued. Pass all.x = TRUE when the left frame is the record of truth, then check for NA in the columns that came from the right.
  1. Trusting merge's row order or column order. It groups rows by the join key and moves that key to the first column. Re-sort on a unique key afterwards and always index by name.
  1. Relying on recycling to fill a column. A length-1 value becoming a constant is intentional; a length-2 value becoming an alternating pattern almost never is. Only lengths that divide the row count recycle, so the harmless case errors and the harmful case does not.
  1. Confusing row names with row positions. After any order or filter, df["3", ] selects the row labelled 3 while df[3, ] selects the third row. Call rownames(df) <- NULL after reordering unless the history matters.
  1. Using == to compare accumulated doubles. Two totals summed in different orders can differ in the last bit. Use isTRUE(all.equal(a, b)), which applies a tolerance and returns a plain logical.
  1. Growing a frame with rbind inside a loop. Each call copies the entire frame, turning a linear job into a quadratic one. Build a list of frames and call do.call(rbind, parts) once, or preallocate the columns.
  1. Assuming nrow works on whatever you were handed. If a drop turned the frame into a vector, nrow returns NULL rather than erroring, and for (i in seq_len(nrow(x))) then quietly iterates zero times -- an empty report instead of a crash.

Best Practices

  • Index columns by name, never by position; a column added upstream or a merge that reorders the frame breaks positional code without a single error message.
  • Write drop = FALSE on every [ , ] selection inside a function, so the return shape is a decision you made rather than a consequence of how many columns the caller passed.
  • Set stringsAsFactors = FALSE explicitly on any frame you build, even on R 4.x where it is already the default; the line documents the intent and survives being run on an older installation.
  • Reorder frames with a row index from order, and reset rownames to NULL immediately afterwards unless you have a specific use for the old labels.
  • State the join type on every merge, and follow an outer join with an explicit count of the NA values it introduced before any totals are computed.
  • Do the arithmetic on whole columns and reserve loops for output; vectorised column operations are both faster and shorter than the row loop that replaces them.
  • Use an ordered factor for status-like columns so tallies come out in a sensible order rather than alphabetically, and so an unexpected value shows up as NA instead of a new category.
  • Check totals against an independently computed total -- line level against group level -- with isTRUE(all.equal(...)), and print the result, so a broken join announces itself on the sheet.

Practice Exercises

  1. Build a frame of six sensor readings with columns sensor, site and reading, then write a function worst(df, n) that returns the n rows with the highest readings as a data frame. Make it correct for n = 1 as well as n = 3, and prove it by printing dim of both results.
  1. Take the goods-inwards program and add a sixth line for a part "RIVET" that does not appear in prices. Run it unchanged and confirm the sheet still reconciles while the line is missing, then switch the merge to all.x = TRUE and print the count of lines with an NA unit price.
  1. Write retag(df, col) that converts a character column into an ordered factor whose levels are its sorted unique values, then prove the conversion is lossless by comparing as.character of the result against the original with identical.
  1. Demonstrate the row-tearing bug and its fix in one script: build a four-row frame, produce a version sorted correctly and a version where only the numeric column was sorted, and print the value paired with one named key under all three to show which two agree.