tidyverse / purrr

A functional programming toolkit for R

Home Page:https://purrr.tidyverse.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

keep_at documentation says to use vars, but doing this yields a warning that vars is deprecated

shearerpmm opened this issue · comments

Now that vars is deprecated, what is the right way to write this code?

library(tidyverse)
x <- c(a = 1, b = 2, c = 3, cat = 10, dog = 15, elephant = 5, e = 10)

x %>% keep_at(vars(starts_with('c')))
#> Warning: Using `vars()` in .at was deprecated in purrr 1.0.0.
#>   c cat 
#>   3  10

x %>% keep_at(starts_with('c'))
#> Error:
#> ! `starts_with()` must be used within a *selecting* function.
#> ℹ See <https://tidyselect.r-lib.org/reference/faq-selection-context.html> for
#>   details.

#> Backtrace:
#>     ▆
#>  1. ├─x %>% keep_at(starts_with("c"))
#>  2. ├─purrr::keep_at(., starts_with("c"))
#>  3. │ └─purrr:::where_at(x, at, user_env = caller_env())
#>  4. │   └─rlang::is_formula(at)
#>  5. └─tidyselect::starts_with("c")
#>  6.   ├─vars %||% peek_vars(fn = "starts_with")
#>  7.   └─tidyselect::peek_vars(fn = "starts_with")
#>  8.     └─cli::cli_abort(...)
#>  9.       └─rlang::abort(...)

using x %>% keep_at(grepl("^c", names(.)))?

using x %>% keep_at(grepl("^c", names(.)))?

you don't need the names() in there because the function in at in keep_at() already operates on the names of the vector.

purrr::keep_at(x, \(x) grepl("^c", x))

Or purrr::keep_at(x, \(x) startsWith(x, "c")) 😄