Subsetting and Cleaning
Ordering Rows
Sorting by a Column
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 = "")
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 colsscoresranked ← 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 colsscoreswinner ← Lin
2ranked <- scores[order(scores$points, decreasing = TRUE), ]3winner <- ranked$name[1]4cat(winner, "\n", sep = "")values this stepLinwinnerLinranked$name[1]cat(winner, " ", sep = "")
3winner <- ranked$name[1]4cat(winner, "\n", sep = "")outputLinvalues this stepLinwinner
Follow the Sort
scoresstarts with Ada9, Lin12, and Mia10.order(scores$points, decreasing = TRUE)ranks the highest points first.- The row order becomes Lin, Mia, Ada.
winner <- ranked$name[1]reads the first ranked name.- 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.