I am trying to sort the columns in a data frame using sort_by()
. I would like to specify which columns to sort using an external vector. We can see the following works.
# using the examples in the help section, this works
sort_by(mtcars, ~ list(am, mpg))
But, I would like to use a vector of variables instead of manually specifying them each time. I am doing this because I'm writing a function that is sorting the columns automatically and I don't know which ones to sort as it depends on the arguments in the function. So it'd be something like this:
# make a vector of variables
name_vec <- c("am", "mpg")
# sort the data by the vector of variables
sort_by(mt_cars, ~ list(name_vec))
However, this is the result when I do that:
I know I can use dplyr::arrange, like this:
dplyr::arrange(mtcars, dplyr::across(tidy select::all_of(vec_name)))
instead of sort_by, but I would rather use a base package if possible.
Try any of these:
sort_by(mtcars, mtcars[name_vec])
mtcars |> list(x = _) |> with(sort_by(x, x[name_vec]))
library(magrittr)
mtcars %>% sort_by(.[name_vec])
sort_by(mtcars, reformulate(name_vec))