- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to sort a data frame in R by multiple columns together?
We can sort a data frame by multiple columns using order function.
Example
Consider the below data frame −
> df <- data.frame(x1 = factor(c("Hi", "Med", "Hi", "Low"), levels = c("Low", "Med", "Hi"), ordered = TRUE), x2 = c("A", "B", "D", "C"), x3 = c(4, 7, 5, 3), x4 = c(9, 5, 7, 4)) > df x1 x2 x3 x4 1 Hi A 4 9 2 Med B 7 5 3 Hi D 5 7 4 Low C 3 4
Let’s say we want to sort the data frame by column x4 in descending order then by column x1 in ascending order.
It can be done follows −
> df[with(df, order(-x4, x1)), ] x1 x2 x3 x4 1 Hi A 4 9 3 Hi D 5 7 2 Med B 7 5 4 Low C 3 4
We can do it by using column index as well −
> df[order(-df[,4], df[,1]), ] x1 x2 x3 x4 1 Hi A 4 9 3 Hi D 5 7 2 Med B 7 5 4 Low C 3 4
- Related Articles
- How to change a data frame with comma separated values in columns to multiple columns in R?
- How to convert multiple columns into single column in an R data frame?
- MySQL query to sort multiple columns together in a single query
- Find the mean of multiple columns based on multiple grouping columns in R data frame.
- How to create a subset of an R data frame based on multiple columns?
- How to drop data frame columns in R by using column name?
- How to divide data frame rows by number of columns in R?
- Find the percentiles for multiple columns in an R data frame.
- How to subset rows based on criterion of multiple numerical columns in R data frame?
- How to combine multiple columns into one in R data frame without using column names?
- How to convert first letter of multiple string columns into capital in R data frame?
- How to standardize columns in an R data frame?
- How to standardize selected columns in R data frame?
- How to Sort CSV by multiple columns in Python ?
- How to convert a vector to data frame in R by defining number of columns?

Advertisements