Menu
Coddy logo textTech

Sorting Vectors

Part of the Logic & Flow section of Coddy's R journey. Lesson 37 of 64.

sort(x) returns the values of x in increasing order, and decreasing = TRUE reverses it. The original vector is not changed:

scores <- c(72, 95, 60, 88)
print(sort(scores))
print(sort(scores, decreasing = TRUE))
print(scores)

Output:

[1] 60 72 88 95
[1] 95 88 72 60
[1] 72 95 60 88

Text is sorted alphabetically. The exact order depends on the system's language settings: on Coddy, as on many servers, capital letters come before lower-case ones, so "Zed" sorts before "ada". Convert with tolower() when case should not matter:

names <- c("cy", "Zed", "ada")
print(sort(names))
print(sort(tolower(names)))

Output:

[1] "Zed" "ada" "cy" 
[1] "ada" "cy"  "zed"

rev(x) reverses the current order without sorting, and head(x, n) keeps the first n elements, which together with sort() gives a top list:

scores <- c(72, 95, 60, 88)
print(rev(scores))
print(head(sort(scores, decreasing = TRUE), 2))

Output:

[1] 88 60 95 72
[1] 95 88

A sorted named vector keeps each name with its value, so the names come out in the order of the values:

stock <- c(tea = 12, jam = 3, oil = 7)
low_first <- sort(stock)
print(names(low_first))
print(low_first[["jam"]])

Output:

[1] "jam" "oil" "tea"
[1] 3
challenge icon

Challenge

Easy

Complete top_scores(scores, n). Return the n highest scores from high to low, joined with , . If there are fewer than n scores, return all of them.

The supplied code reads the scores as a comma-separated line and n, and prints the returned value.

Try it yourself

top_scores <- function(scores, n) {
  # Write your code here
  ""
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(top_scores(as.numeric(strsplit(input[1], ",")[[1]]), as.numeric(input[2])), 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