How to order an R dataframe by one column in descending order and another in ascending order? R order()
function provides a way to sort each column in a different order. Also, you can use the arrange()
function with desc()
to specify the descending order.
First, let’s create a DataFrame from vectors in R
# Create Data Frame
df=data.frame(id=c(11,22,33,44,55),
name=c("spark","python","R","jsp","java"),
price=c(144,NA,321,567,567),
publish_date= as.Date(
c("2007-06-22", "2004-02-13", "2006-05-18",
"2010-09-02","2007-07-20"))
)
Yields below output.
1. Using order()
Now, by using the order()
function you can sort the data frame first by ascending order on the price
column and then descending order on the id
column. To sort the column in descending order, prefix the sorting variable with a minus sign.
# Sort DataFrame on one column
df2 <- df[order(df$price),]
df2
# Sort DataFrame one in ascending and another in descending
df2 <- df[order(df$price,-df$id),]
df2
Yields below output.
2. Sort by dplyr Package
Alternatively, you can use the arrange() function from the dplyr package to sort the dataframe in R, to sort one column in ascending and another column in descending order, pass both columns comma separated to the arrange() function, and use desc()
to arrange in descending order. For more details refer to sort dataframe by multiple columns
# Load dplyr library
library(dplyr)
df2 <- df %>% arrange(price, desc(id))
df2
Yields the same output as above.
Related Articles
- Sort or Order List in R?
- Sort Table in R with Examples
- R Sort Vector
- R Sort by Date
- Reorder Column Names of DataFrame in R