| 1 |
#' Select variables with a function |
| 2 |
#' |
| 3 |
#' This [selection helper][language] selects the variables for which a |
| 4 |
#' function returns `TRUE`. |
| 5 |
#' |
| 6 |
#' @param fn A function that returns `TRUE` or `FALSE` (technically, a |
| 7 |
#' _predicate_ function). Can also be a purrr-like formula. |
| 8 |
#' |
| 9 |
#' @section Examples: |
| 10 |
#' |
| 11 |
#' ```{r, child = "man/rmd/setup.Rmd"} |
| 12 |
#' ``` |
| 13 |
#' |
| 14 |
#' Selection helpers can be used in functions like `dplyr::select()` |
| 15 |
#' or `tidyr::pivot_longer()`. Let's first attach the tidyverse: |
| 16 |
#' |
| 17 |
#' ```{r, comment = "#>", collapse = TRUE} |
| 18 |
#' library(tidyverse) |
| 19 |
#' |
| 20 |
#' # For better printing |
| 21 |
#' iris <- as_tibble(iris) |
| 22 |
#' ``` |
| 23 |
#' |
| 24 |
#' `where()` takes a function and returns all variables for which the |
| 25 |
#' function returns `TRUE`: |
| 26 |
#' |
| 27 |
#' ```{r, comment = "#>", collapse = TRUE} |
| 28 |
#' is.factor(iris[[4]]) |
| 29 |
#' |
| 30 |
#' is.factor(iris[[5]]) |
| 31 |
#' |
| 32 |
#' iris %>% select(where(is.factor)) |
| 33 |
#' |
| 34 |
#' is.numeric(iris[[4]]) |
| 35 |
#' |
| 36 |
#' is.numeric(iris[[5]]) |
| 37 |
#' |
| 38 |
#' iris %>% select(where(is.numeric)) |
| 39 |
#' ``` |
| 40 |
#' |
| 41 |
#' |
| 42 |
#' ## The formula shorthand |
| 43 |
#' |
| 44 |
#' You can use purrr-like formulas as a shortcut for creating a |
| 45 |
#' function on the spot. These expressions are equivalent: |
| 46 |
#' |
| 47 |
#' ```{r, comment = "#>", collapse = TRUE} |
| 48 |
#' iris %>% select(where(is.numeric)) |
| 49 |
#' |
| 50 |
#' iris %>% select(where(function(x) is.numeric(x))) |
| 51 |
#' |
| 52 |
#' iris %>% select(where(~ is.numeric(.x))) |
| 53 |
#' ``` |
| 54 |
#' |
| 55 |
#' The shorthand is useful for adding logic inline. Here we select all |
| 56 |
#' numeric variables whose mean is greater than 3.5: |
| 57 |
#' |
| 58 |
#' ```{r, comment = "#>", collapse = TRUE} |
| 59 |
#' iris %>% select(where(~ is.numeric(.x) && mean(.x) > 3.5)) |
| 60 |
#' ``` |
| 61 |
#' |
| 62 |
#' @export |
| 63 |
where <- function(fn) { |
| 64 |
predicate <- as_function(fn) |
| 65 |
call <- current_call() |
| 66 |
|
| 67 |
function(x, ...) { |
| 68 |
out <- predicate(x, ...) |
| 69 |
check_predicate_output(out, call = call) |
| 70 |
|
| 71 |
out |
| 72 |
} |
| 73 |
} |