Menu
Coddy logo textTech

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 3
challenge icon

Challenge

Easy

Complete 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")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online R compiler