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.

Advertisements

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.

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),]
df2

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

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
library(dplyr)
df2 <- df %>% arrange(price, desc(id))
df2

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