Order DataFrame by one descending and one ascending column in R

Spread the love

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 (NNK)

SparkByExamples.com is a Big Data and Spark examples community page, all examples are simple and easy to understand and well tested in our development environment Read more ..

Leave a Reply

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