Sorting by a Key
Part of the Logic & Flow section of Coddy's R journey. Lesson 38 of 64.
order(x) returns the positions that would sort x: first the position of the smallest value, then the next one, and so on. Index another vector with it to sort that vector by x:
names <- c("cy", "ada", "bo")
ages <- c(41, 36, 22)
print(order(ages))
print(names[order(ages)])Output:
[1] 3 2 1
[1] "bo" "ada" "cy" For decreasing order, pass decreasing = TRUE, or put a minus sign in front of a numeric key:
names <- c("cy", "ada", "bo")
scores <- c(80, 95, 80)
print(names[order(scores, decreasing = TRUE)])
print(names[order(-scores)])Output:
[1] "ada" "cy" "bo"
[1] "ada" "cy" "bo" Give order() a second key to break ties. Here the scores sort from high to low and equal scores sort by name:
names <- c("cy", "ada", "bo")
scores <- c(80, 95, 80)
print(names[order(-scores, names)])Output:
[1] "ada" "bo" "cy" order() keeps tied values in their original order when no second key is given. The same positions can reorder several vectors that belong together:
items <- c("tea", "jam", "oil")
price <- c(4, 2.5, 4)
qty <- c(1, 6, 3)
idx <- order(price)
print(items[idx])
print(qty[idx])Output:
[1] "jam" "tea" "oil"
[1] 6 1 3Challenge
EasyComplete ranking(names, scores). Return one line per player, 1. ada 95, from the highest score to the lowest. Players with the same score are listed alphabetically.
The supplied code reads the players as name:score pairs separated by commas and prints each returned line.
Try it yourself
ranking <- function(names, scores) {
# Write your code here
character(0)
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
pairs <- strsplit(strsplit(input[1], ",")[[1]], ":")
names <- sapply(pairs, function(p) p[1])
values <- as.numeric(sapply(pairs, function(p) p[2]))
cat(ranking(names, values), sep = "\n")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Substrings with substr()Formatting with sprintf()Splitting and JoiningSearching StringsReplacing TextRecap - Username Builder4Matrices
Creating MatricesIndexing MatricesRow and Column SummariesMatrix ArithmeticRecap - Seating Chart2Key-Value Lookups
Named Vector LookupsChecking KeysAdding and Removing KeysLooping Over NamesRecap - Stock Desk8Sorting and Grouping
Sorting VectorsSorting by a KeyGrouping with split()Group SummariesRecap - Leaderboard3Sets and Counting
Unique ValuesSet OperationsMembership TestsCounting with table()Recap - Event Guests6Functions as Values
Anonymous FunctionsPassing FunctionsReturning FunctionsClosures with StateRecap - Discount Rules9Data Frames
Creating Data FramesColumns and RowsFiltering RowsAdding and SortingRecap - Sales Report12Project - Expense Tracker
Recording ExpensesTotal SpendingPractice on your own: Online R compiler