Skip to contents

Arrange data frame rows by columns. Ties can be arranged by adding another column name. Use desc() to arrange a column in descending order. arrange_() allows passing variable names as a character vector.

Usage

arrange(.data, ...)

# S3 method for class 'data.frame'
arrange(.data, ...)

# S3 method for class 'group_df'
arrange(.data, ..., .by_group = FALSE)

# S3 method for class 'nest_df'
arrange(.data, ...)

arrange_(data, x, ...)

# S3 method for class 'data.frame'
arrange_(data, x, ...)

# S3 method for class 'group_df'
arrange_(data, x, by_group = FALSE, ...)

# S3 method for class 'nest_df'
arrange_(data, x, ...)

Arguments

.data, data

A data frame.

...

Unquoted column names to sort the data by. Use desc() to arrange in descending order. Or further arguments passed to or from other methods.

.by_group, by_group

TRUE or FALSE. Applies to group_df data frames. If TRUE, then the data frame will be arranged by the grouping variables first.

x

A character vector of column names to sort the data by. Use desc() to arrange in descending order.

Value

data.frame

Details

  • NAs are placed at the end of the data frame.

  • Data frame attributes may be dropped.

  • There are no checks for duplicate column names. The first occurrence will be sorted on if so.

  • List-columns cannot be arranged on. If you are arranging on a nest_df, then data frame columns inside the list-column can also be arranged on.

  • If no variables are supplied to arrange on, then it will return an error.

To limit unwanted namespace conflicts, the expression is evaluated in an environment that only contains the data frame and the functions base::order() and desc().

Examples

#----------------------------------------------------------------------------
# arrange() examples
#----------------------------------------------------------------------------
library(bkdat)

df1 <- data.frame(a = c(1, 2, 3), b = c(6, 5, 4))
df2 <- data.frame(a = c(1, 2, 2), b = c(4, 6, 5))

# Arrange by 'a' and then by descending 'a'.
arrange_(df1, "a")
#>   a b
#> 1 1 6
#> 2 2 5
#> 3 3 4
arrange_(df1, "desc(a)")
#>   a b
#> 1 3 4
#> 2 2 5
#> 3 1 6

arrange(df1, a)
#>   a b
#> 1 1 6
#> 2 2 5
#> 3 3 4
arrange(df1, desc(a))
#>   a b
#> 1 3 4
#> 2 2 5
#> 3 1 6

# Arrange by descending 'a' while sorting ties with 'b'.
arrange_(df2, c("desc(a)", "b"))
#>   a b
#> 1 2 5
#> 2 2 6
#> 3 1 4
arrange(df2, desc(a), b)
#>   a b
#> 1 2 5
#> 2 2 6
#> 3 1 4