order() for Flexible Ordering
Get the index permutation to sort by one or multiple criteria.
order() for Flexible Ordering is a free R Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, and your progress syncs across the web and the CoddyKit app. The R Academy course includes 4 lessons in total.
What order() Returns
order() does not return sorted values — it returns the indices that would sort the vector. This indirection makes it far more powerful than sort() because you can apply those indices to any related structure.
x <- c(30, 10, 50, 20, 40)
indices <- order(x)
print(indices)
# Verify: x[indices] gives sorted x
print(x[indices])order() in Descending Order
Like sort(), order() accepts decreasing = TRUE to return indices that produce a descending sequence. This is useful for sorting from largest to smallest.
scores <- c(78, 92, 65, 88, 71)
desc_order <- order(scores, decreasing = TRUE)
cat('Rank order (index):', desc_order, '\n')
cat('Scores high to low:', scores[desc_order], '\n')Sorting a Data Frame by One Column
The most practical use of order() is sorting a data frame by one of its columns. Pass the column to order(), then use those indices to reorder all rows of the data frame.
df <- data.frame(
name = c('Charlie', 'Alice', 'Bob', 'Diana'),
age = c(35, 28, 42, 31)
)
sorted_df <- df[order(df$age), ]
print(sorted_df)Sorting a Data Frame Descending
To sort a data frame from largest to smallest on a numeric column, pass decreasing = TRUE to order(). Row names (indices) in the output reflect original positions.
products <- data.frame(
item = c('Pen', 'Notebook', 'Stapler', 'Tape'),
price = c(1.5, 4.99, 7.25, 2.10)
)
products[order(products$price, decreasing = TRUE), ]Multi-Column Ordering
Pass multiple vectors to order() separated by commas. R sorts by the first argument, then breaks ties using the second, third, and so on. This mirrors SQL's ORDER BY clause behavior.
df <- data.frame(
dept = c('HR', 'IT', 'HR', 'IT', 'HR'),
salary = c(50000, 70000, 60000, 65000, 55000)
)
# Sort by dept first, then by salary within dept
df[order(df$dept, df$salary), ]Mixed Ascending/Descending Multi-Sort
To sort one column ascending and another descending, negate the descending numeric column with -. For character columns, use xtfrm() to get a sortable integer representation and then negate it.
df <- data.frame(
dept = c('HR', 'IT', 'HR', 'IT', 'HR'),
salary = c(50000, 70000, 60000, 65000, 55000)
)
# dept ascending, salary descending
df[order(df$dept, -df$salary), ]Handling NA in order()
order() also has an na.last argument, just like sort(). By default, na.last = NA which puts NAs last. Set na.last = TRUE or na.last = FALSE to control their placement explicitly.
vals <- c(5, NA, 2, NA, 8, 1)
# Default: NAs sorted last
order(vals)
# NAs first
order(vals, na.last = FALSE)Preserving Row Names After Sorting
When you subset a data frame with row indices, R keeps the original row names. Use row.names(df) <- NULL or reset= approaches to reset them to 1, 2, 3, ... after sorting.
df <- data.frame(
city = c('Paris', 'Tokyo', 'NYC'),
pop = c(2.1, 13.9, 8.3)
)
sorted <- df[order(df$pop), ]
print(sorted)
# Reset row names
row.names(sorted) <- NULL
print(sorted)order() vs sort() Side by Side
The key difference: sort(x) returns sorted values; order(x) returns sorted positions. Use sort() when you only need the values; use order() when you need to rearrange related data structures together.
x <- c(50, 20, 80, 10, 60)
cat('sort(x) :', sort(x), '\n')
cat('order(x) :', order(x), '\n')
cat('x[order(x)]:', x[order(x)], '\n')Sorting a Data Frame by String Column
You can sort by character columns too. order(df$name) returns row indices in alphabetical order of the name column, which you then use to reorder the data frame.
employees <- data.frame(
name = c('Zara', 'Ahmed', 'Maria', 'Bruno'),
tenure = c(3, 7, 2, 5)
)
employees[order(employees$name), ]Chaining order() for Complex Sorts
Three-level sorting is straightforward: pass three vectors to order(). Each additional argument is used as a tiebreaker for equal values in the previous arguments.
df <- data.frame(
region = c('West', 'East', 'West', 'East', 'West'),
dept = c('HR', 'IT', 'HR', 'IT', 'IT'),
score = c(85, 90, 78, 88, 92)
)
df[order(df$region, df$dept, df$score), ]Quick Check
What does order(x) return when applied to a vector x?
order() Key Takeaways
Key takeaways for order():
order(x)returns indices, not values — usex[order(x)]to get sorted values- Sort data frames with
df[order(df$col), ] - Multi-column sort:
order(df$a, df$b)— ties inaare broken byb - Negate numeric columns with
-for descending in multi-sort - Control NA placement with
na.last = TRUE/FALSE/NA - Unlike
sort(),order()lets you sort parallel structures together
df <- data.frame(
name = c('Eve', 'Bob', 'Alice', 'Charlie'),
score = c(88, 92, 88, 75)
)
# Sort by score descending, then name ascending for ties
df[order(-df$score, df$name), ]Learn R with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 43
- Lessons
- 159
Frequently Asked Questions
Is the “order() for Flexible Ordering” lesson free?
Yes — any 3 lessons of the R Academy learning path, including “order() for Flexible Ordering”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The R Academy course includes 4 lessons in total.
What will I learn in “order() for Flexible Ordering”?
Get the index permutation to sort by one or multiple criteria. 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, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.
How long does the “order() for Flexible Ordering” 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