Flow and Data
Data Frames
Columns that Travel Together
A data frame keeps related columns aligned by row. New columns can be computed from existing columns.
Program
Play the script to see quantities become row totals, then one grand total.
data_frames.R
Replay: real traced execution (multi-file project)
sales <- data.frame(item = c("book", "pen"), qty = c(2, 5))
sales$total <- sales$qty * 3
grand_total <- sum(sales$total)
cat(grand_total, "\n", sep = "")
sales ← 2 rows x 2 cols
1sales <- data.frame(item = c("book", "pen"), qty = c(2, 5))2sales$total <- sales$qty * 3values this step2 rows x 2 colssalessales ← 2 rows x 3 cols
1sales <- data.frame(item = c("book", "pen"), qty = c(2, 5))2sales$total <- sales$qty * 33grand_total <- sum(sales$total)values this step2 rows x 2 cols → 2 rows x 3 colssalesgrand_total ← 21
2sales$total <- sales$qty * 33grand_total <- sum(sales$total)4cat(grand_total, "\n", sep = "")values this step21grand_total6, 15sales$totalcat(grand_total, " ", sep = "")
3grand_total <- sum(sales$total)4cat(grand_total, "\n", sep = "")output21values this step21grand_total
Add a Total Column
salesstarts with item and quantity columns.- Each row total is
qty * 3. sales$totalstores the row totals.sum(sales$total)adds the row totals into21. | Item | Quantity | Row total | | --- | --- | --- | |book|2|6| |pen|5|15|
data.frame
`data.frame` creates a table with named columns.
column assignment
`sales$total <- ...` adds or replaces a column.
column sum
`sum(sales$total)` adds all values in one column.
Exercise: data_frames.R
Create a sales data frame, add row totals from quantity, and print the grand total