Data Analysis
Reshape
Wide to Long
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 = "")
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 colswidelong ← 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 colswidetotal ← 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$valuecat(total, " ", sep = "")
3total <- sum(long$value)4cat(total, "\n", sep = "")output18values this step18total
Follow the Reshape
- The wide data has Monday values
3and5. - It has Tuesday values
4and6. - The long data makes one row per day and period.
- The four long values are
3,4,5, and6. - Those values add to
18, so the script prints18. | 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.