Skip to contents

Sorts a dataframe by one or more variables, and returns the result along with tidyverse code used to generate it.

Usage

sort_vars(data, vars, asc = rep(TRUE, length(vars)))

Arguments

data

a dataframe to sort

vars

a character vector of variable names to sort by

asc

logical, length of 1 or same length as vars. If TRUE (default), then sorted in ascending order, otherwise descending.

Value

data with tidyverse code attached

See also

Author

Owen Jin, Zhaoming Su

Examples

sorted <- sort_vars(iris,
    vars = c("Sepal.Width", "Sepal.Length"),
    asc = c(TRUE, FALSE)
)
cat(code(sorted))
#> iris |> dplyr::arrange(Sepal.Width, desc(Sepal.Length))
head(sorted)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
#> 1          5.0         2.0          3.5         1.0 versicolor
#> 2          6.2         2.2          4.5         1.5 versicolor
#> 3          6.0         2.2          4.0         1.0 versicolor
#> 4          6.0         2.2          5.0         1.5  virginica
#> 5          6.3         2.3          4.4         1.3 versicolor
#> 6          5.5         2.3          4.0         1.3 versicolor