Order and sort vectors

vec_order(x, direction = c("asc", "desc"), na_value = c("largest", "smallest"))

vec_sort(x, direction = c("asc", "desc"), na_value = c("largest", "smallest"))

## Arguments

x A vector Direction to sort in. Defaults to ascending. Should NAs be treated as the largest or smallest values?

## Value

• vec_order() an integer vector the same size as x.

• vec_sort() a vector with the same size and type as x.

## Differences with order()

Unlike the na.last argument of order() which decides the positions of missing values irrespective of the decreasing argument, the na_value argument of vec_order() interacts with direction. If missing values are considered the largest value, they will appear last in ascending order, and first in descending order.

## Dependencies of vec_order()

• vec_proxy_order()

## Dependencies of vec_sort()

• vec_proxy_order()

• vec_order()

• vec_slice()

## Examples

x <- round(c(runif(9), NA), 3)
vec_order(x)
#>  [1]  4  3  9  6  7  5  8  1  2 10
vec_sort(x)
#>  [1] 0.359 0.500 0.567 0.584 0.634 0.775 0.859 0.888 0.996    NA
vec_sort(x, "desc")
#>  [1]    NA 0.996 0.888 0.859 0.775 0.634 0.584 0.567 0.500 0.359

# Can also handle data frames
df <- data.frame(g = sample(2, 10, replace = TRUE), x = x)
vec_order(df)
#>  [1]  4  3  6  7  1  2  9  5  8 10
vec_sort(df)
#>    g     x
#> 1  1 0.359
#> 2  1 0.500
#> 3  1 0.584
#> 4  1 0.634
#> 5  1 0.888
#> 6  1 0.996
#> 7  2 0.567
#> 8  2 0.775
#> 9  2 0.859
#> 10 2    NA
vec_sort(df, "desc")
#>    g     x
#> 1  2    NA
#> 2  2 0.859
#> 3  2 0.775
#> 4  2 0.567
#> 5  1 0.996
#> 6  1 0.888
#> 7  1 0.634
#> 8  1 0.584
#> 9  1 0.500
#> 10 1 0.359

# Missing values interpreted as largest values are last when
# in increasing order:
vec_order(c(1, NA), na_value = "largest", direction = "asc")
#> [1] 1 2
vec_order(c(1, NA), na_value = "largest", direction = "desc")
#> [1] 2 1