Debian Codegraph @

R/helpers-misc.R

raw
1 #' Select all variables or the last variable
2 #'
3 #' @description
4 #'
5 #' These functions are [selection helpers][language].
6 #'
7 #' * [everything()] selects all variable. It is also useful in
8 #' combination with other tidyselect operators.
9 #'
10 #' * [last_col()] selects the last variable.
11 #'
12 #' @inheritParams starts_with
13 #'
14 #' @section Examples:
15 #'
16 #' ```{r, child = "man/rmd/setup.Rmd"}
17 #' ```
18 #'
19 #' Selection helpers can be used in functions like `dplyr::select()`
20 #' or `tidyr::pivot_longer()`. Let's first attach the tidyverse:
21 #'
22 #' ```{r, comment = "#>", collapse = TRUE}
23 #' library(tidyverse)
24 #'
25 #' # For better printing
26 #' iris <- as_tibble(iris)
27 #' mtcars <- as_tibble(mtcars)
28 #' ```
29 #'
30 #' Use `everything()` to select all variables:
31 #'
32 #' ```{r, comment = "#>", collapse = TRUE}
33 #' iris %>% select(everything())
34 #'
35 #' mtcars %>% pivot_longer(everything())
36 #' ```
37 #'
38 #' Use `last_col()` to select the last variable:
39 #'
40 #' ```{r, comment = "#>", collapse = TRUE}
41 #' iris %>% select(last_col())
42 #'
43 #' mtcars %>% pivot_longer(last_col())
44 #' ```
45 #'
46 #' Supply an offset `n` to select a variable located `n` positions
47 #' from the end:
48 #'
49 #' ```{r, comment = "#>", collapse = TRUE}
50 #' mtcars %>% select(1:last_col(5))
51 #' ```
52 #'
53 #' @seealso `r rd_helpers_seealso()`
54 #' @export
55 everything <- function(vars = NULL) {
56 vars <- vars %||% peek_vars(fn = "everything")
57 seq_along(vars)
58 }
59
60 #' @rdname everything
61 #' @export
62 #' @param offset Set it to `n` to select the nth var from the end.
63 last_col <- function(offset = 0L, vars = NULL) {
64 if (!is_integerish(offset, n = 1)) {
65 not <- obj_type_friendly(offset)
66 cli::cli_abort("{.arg offset} must be a single integer, not {not}.")
67 }
68
69 vars <- vars %||% peek_vars(fn = "last_col")
70 n <- length(vars)
71
72 if (offset && n <= offset) {
73 cli::cli_abort("{.arg offset} ({offset}) must be smaller than the number of columns ({n}).")
74 } else if (n == 0) {
75 cli::cli_abort("Can't select last column when input is empty.")
76 } else {
77 n - as.integer(offset)
78 }
79 }