order returns row positions in sorted order. Data frames use those positions to rearrange rows.

Program

Play the script to rank rows by points and choose the winner.

ordering.R
Replay: real traced execution (multi-file project)
scores <- data.frame(name = c("Ada", "Lin", "Mia"), points = c(9, 12, 10))
ranked <- scores[order(scores$points, decreasing = TRUE), ]
winner <- ranked$name[1]
cat(winner, "\n", sep = "")
  1. scores ← 3 rows x 2 cols

    1scores <- data.frame(name = c("Ada", "Lin", "Mia"), points = c(9, 12, 10))2ranked <- scores[order(scores$points, decreasing = TRUE), ]
    values this step3 rows x 2 colsscores
  2. ranked ← 3 rows x 2 cols

    1scores <- data.frame(name = c("Ada", "Lin", "Mia"), points = c(9, 12, 10))2ranked <- scores[order(scores$points, decreasing = TRUE), ]3winner <- ranked$name[1]
    values this step3 rows x 2 colsranked3 rows x 2 colsscores
  3. winner ← Lin

    2ranked <- scores[order(scores$points, decreasing = TRUE), ]3winner <- ranked$name[1]4cat(winner, "\n", sep = "")
    values this stepLinwinnerLinranked$name[1]
  4. cat(winner, " ", sep = "")

    3winner <- ranked$name[1]4cat(winner, "\n", sep = "")
    outputLin
    values this stepLinwinner

Follow the Sort

  1. scores starts with Ada 9, Lin 12, and Mia 10.
  2. order(scores$points, decreasing = TRUE) ranks the highest points first.
  3. The row order becomes Lin, Mia, Ada.
  4. winner <- ranked$name[1] reads the first ranked name.
  5. The script prints Lin. | rank | name | points | | --- | --- | --- | | 1 | Lin | 12 | | 2 | Mia | 10 | | 3 | Ada | 9 |
order `order(scores$points)` returns row positions sorted by points.
decreasing `decreasing = TRUE` sorts highest values first.
row subset `scores[rows, ]` reorders the rows and keeps every column.

Exercise: ordering.R

Reproduce the printed winner Lin, then identify the sorted row order from highest points to lowest.