Created
May 6, 2022 02:03
-
-
Save jonocarroll/9efdaddab7b27d81bcdcbc5229bf6f65 to your computer and use it in GitHub Desktop.
{tidyselect} columns with alphabetical ordering
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| starts_with_ordered <- function(match, decreasing = FALSE) { | |
| all_vars <- tidyselect::peek_vars() | |
| matches <- tidyselect::starts_with(match) | |
| named_matches <- setNames(matches, all_vars[matches]) | |
| named_matches[order(names(named_matches), decreasing = decreasing)] | |
| } | |
| mtcars |> | |
| dplyr::select(starts_with_ordered("c", decreasing = FALSE)) |> | |
| head() | |
| #> carb cyl | |
| #> Mazda RX4 4 6 | |
| #> Mazda RX4 Wag 4 6 | |
| #> Datsun 710 1 4 | |
| #> Hornet 4 Drive 1 6 | |
| #> Hornet Sportabout 2 8 | |
| #> Valiant 1 6 | |
| mtcars |> | |
| dplyr::select(starts_with_ordered("c", decreasing = TRUE)) |> | |
| head() | |
| #> cyl carb | |
| #> Mazda RX4 6 4 | |
| #> Mazda RX4 Wag 6 4 | |
| #> Datsun 710 4 1 | |
| #> Hornet 4 Drive 6 1 | |
| #> Hornet Sportabout 8 2 | |
| #> Valiant 6 1 | |
| mtcars |> | |
| dplyr::select(starts_with_ordered("d", decreasing = FALSE)) |> | |
| head() | |
| #> disp drat | |
| #> Mazda RX4 160 3.90 | |
| #> Mazda RX4 Wag 160 3.90 | |
| #> Datsun 710 108 3.85 | |
| #> Hornet 4 Drive 258 3.08 | |
| #> Hornet Sportabout 360 3.15 | |
| #> Valiant 225 2.76 | |
| mtcars |> | |
| dplyr::select(starts_with_ordered("d", decreasing = TRUE)) |> | |
| head() | |
| #> drat disp | |
| #> Mazda RX4 3.90 160 | |
| #> Mazda RX4 Wag 3.90 160 | |
| #> Datsun 710 3.85 108 | |
| #> Hornet 4 Drive 3.08 258 | |
| #> Hornet Sportabout 3.15 360 | |
| #> Valiant 2.76 225 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment