You are currently viewing Order DataFrame by one descending and one ascending column in R

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
          publish_date= as.Date(
            c("2007-06-22", "2004-02-13", "2006-05-18",

Yields below output.

r sort ascending descending

1. Using order()

Now, by using the order() function let’s sort the DateFrame 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),]

# Sort DataFrame one in ascending and another in descending
df2 <- df[order(df$price,-df$id),]

Yields below output.

r sort each column different order

2. Using arrange()

The arrange() function from the dplyr package is also used to sort 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
df2 <- df %>% arrange(price, desc(id))

Yields the same output as above.

Related Articles

Naveen Nelamali

Naveen Nelamali (NNK) is a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, He has honed his expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. Naveen journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. In this blog, he shares his experiences with the data as he come across. Follow Naveen @ LinkedIn and Medium