Long data stores repeated measurements in rows. This shape is useful for grouped summaries and plotting.

Program

Play the script to turn morning/evening columns into period rows.

reshape_long.R
Replay: real traced execution (multi-file project)
wide <- data.frame(day = c("Mon", "Tue"), morning = c(3, 4), evening = c(5, 6))
long <- data.frame(day = rep(wide$day, 2), period = rep(c("morning", "evening"), each = 2), value = c(wide$morning, wide$evening))
total <- sum(long$value)
cat(total, "\n", sep = "")
  1. wide ← 2 rows x 3 cols

    1wide <- data.frame(day = c("Mon", "Tue"), morning = c(3, 4), evening = c(5, 6))2long <- data.frame(day = rep(wide$day, 2), period = rep(c("morning", "evening"), each = 2), value = c(wide$morning, wide$evening))
    values this step2 rows x 3 colswide
  2. long ← 4 rows x 3 cols

    1wide <- data.frame(day = c("Mon", "Tue"), morning = c(3, 4), evening = c(5, 6))2long <- data.frame(day = rep(wide$day, 2), period = rep(c("morning", "evening"), each = 2), value = c(wide$morning, wide$evening))3total <- sum(long$value)
    values this step4 rows x 3 colslong2 rows x 3 colswide
  3. total ← 18

    2long <- data.frame(day = rep(wide$day, 2), period = rep(c("morning", "evening"), each = 2), value = c(wide$morning, wide$evening))3total <- sum(long$value)4cat(total, "\n", sep = "")
    values this step18total3, 4, 5, 6long$value
  4. cat(total, " ", sep = "")

    3total <- sum(long$value)4cat(total, "\n", sep = "")
    output18
    values this step18total

Follow the Reshape

  1. The wide data has Monday values 3 and 5.
  2. It has Tuesday values 4 and 6.
  3. The long data makes one row per day and period.
  4. The four long values are 3, 4, 5, and 6.
  5. Those values add to 18, so the script prints 18. | day | period | value | | --- | --- | --- | | Mon | morning | 3 | | Tue | morning | 4 | | Mon | evening | 5 | | Tue | evening | 6 | | total | - | 18 |
wide data Wide data stores repeated measurements in separate columns.
long data Long data stores measurement type and value in rows.
rep `rep` repeats values to build aligned columns.

Exercise: reshape_long.R

Reproduce the output 18, then trace the four long rows that add 3 + 4 + 5 + 6.