Sorting Vectors with sort()
Sort numeric and character vectors in ascending or descending order.
Sorting Vectors with sort() is a free R Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Does sort() Do?
The sort() function arranges a vector's elements in ascending order by default. It works on numeric, character, and logical vectors, returning a new sorted vector without modifying the original.
scores <- c(42, 7, 95, 13, 67, 31)
sorted_scores <- sort(scores)
print(sorted_scores)Sorting in Descending Order
Pass decreasing = TRUE to sort() to flip the order. This is useful for ranking results from highest to lowest, such as leaderboard scores or sales figures.
prices <- c(19.99, 5.49, 89.00, 34.50, 12.75)
sort(prices, decreasing = TRUE)Sorting Character Vectors
Character vectors are sorted lexicographically (alphabetically). R uses the system locale for ordering, so uppercase letters may sort before lowercase depending on the locale setting.
fruits <- c('banana', 'Apple', 'cherry', 'apricot', 'Blueberry')
sort(fruits)Case-Sensitive Sorting Behavior
In most locales, uppercase letters sort before lowercase. To sort case-insensitively, convert to a common case first using tolower() or toupper() before sorting.
words <- c('Zebra', 'apple', 'Mango', 'banana')
# Case-sensitive (uppercase first)
sort(words)
# Case-insensitive approach
words[order(tolower(words))]Handling NA Values with na.last
By default, sort() removes NA values. Use na.last = TRUE to put NAs at the end, or na.last = FALSE to put them at the beginning. This controls where missing values land in the result.
data <- c(5, NA, 2, NA, 8, 1)
# Default: NAs removed
sort(data)
# NAs at end
sort(data, na.last = TRUE)
# NAs at beginning
sort(data, na.last = FALSE)Sorting Logical Vectors
Logical vectors sort with FALSE (0) before TRUE (1) in ascending order. This can be useful when you want to group TRUE/FALSE values together.
flags <- c(TRUE, FALSE, TRUE, FALSE, FALSE, TRUE)
sort(flags)
sort(flags, decreasing = TRUE)sort() Preserves Vector Type
sort() always returns a vector of the same type as the input. Sorting integers returns integers, doubles return doubles, and characters return characters. The class attribute is preserved.
int_vec <- c(5L, 2L, 8L, 1L, 4L)
result <- sort(int_vec)
print(result)
print(class(result))
print(typeof(result))sort.int() for Integer Sorting
sort.int() is a lower-level function specifically for sorting integer or double vectors. It accepts the same arguments as sort() but is slightly faster for large numeric vectors because it skips some method dispatch overhead.
big_vec <- c(100L, 3L, 77L, 22L, 55L, 9L)
# sort.int works like sort for numeric/integer vectors
result <- sort.int(big_vec, decreasing = FALSE)
print(result)Original Vector is Unchanged
An important property of sort(): it does not modify the original vector. It returns a new sorted vector. You must assign the result if you want to keep the sorted order.
temps <- c(22.5, 18.0, 30.1, 15.3, 27.8)
sorted_temps <- sort(temps)
cat('Original:', temps, '\n')
cat('Sorted: ', sorted_temps, '\n')Sorting and Indexing Together
Sometimes you need both the sorted values and their original positions. Combine sort() with which() or use order() (covered next lesson) to retrieve original indices alongside sorted values.
exam_scores <- c(78, 92, 65, 88, 71)
sorted <- sort(exam_scores)
cat('Sorted scores:', sorted, '\n')
# Find what rank each original score gets
ranks <- rank(exam_scores)
cat('Rank of each student:', ranks, '\n')Practical sort() Patterns
A common pattern is to sort unique values from a vector, or to get the top-N largest values using sort() combined with head() or tail().
sales <- c(120, 340, 95, 210, 340, 180, 95, 420)
# Unique values in order
sort(unique(sales))
# Top 3 largest
tail(sort(sales), 3)
# Bottom 3 smallest
head(sort(sales), 3)Quick Check
Which argument controls whether NA values appear at the start, end, or are dropped when using sort()?
sort() Key Takeaways
Key takeaways for sort():
- Use
sort(x)for ascending order andsort(x, decreasing=TRUE)for descending - Character vectors sort alphabetically; case matters by default
- Control NA placement with
na.last = TRUE/FALSE/NA sort()does not modify the original vector — always returns a new one- Use
tail(sort(x), n)orhead(sort(x), n)to get top-N or bottom-N values sort.int()is a faster variant for numeric/integer vectors
x <- c(3, 1, NA, 5, 2, NA, 4)
cat('Ascending (no NAs):', sort(x), '\n')
cat('Descending (NAs last):', sort(x, decreasing = TRUE, na.last = TRUE), '\n')Frequently asked questions
Is the “Sorting Vectors with sort()” lesson free?
Yes — the full text of “Sorting Vectors with sort()” is free to read here on the web, and the R Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the R Academy course, upgrade to CoddyKit PRO.
What will I learn in “Sorting Vectors with sort()”?
Sort numeric and character vectors in ascending or descending order. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start R Academy?
No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Sorting Vectors with sort()” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this R Academy lesson?
Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Sorting Vectors with sort()
- order() for Flexible Ordering
- Ranking Values with rank()
- Sorting Data Frames by Column