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 88Text 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 88A 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] 3Challenge
EasyComplete 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")
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