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 = "")
  1. sales ← 2 rows x 2 cols

    1sales <- data.frame(item = c("book", "pen"), qty = c(2, 5))2sales$total <- sales$qty * 3
    values this step2 rows x 2 colssales
  2. sales ← 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 colssales
  3. grand_total ← 21

    2sales$total <- sales$qty * 33grand_total <- sum(sales$total)4cat(grand_total, "\n", sep = "")
    values this step21grand_total6, 15sales$total
  4. cat(grand_total, " ", sep = "")

    3grand_total <- sum(sales$total)4cat(grand_total, "\n", sep = "")
    output21
    values this step21grand_total

Add a Total Column

  1. sales starts with item and quantity columns.
  2. Each row total is qty * 3.
  3. sales$total stores the row totals.
  4. sum(sales$total) adds the row totals into 21. | 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