tidyverse / purrr

A functional programming toolkit for R
https://purrr.tidyverse.org/
Other
1.28k stars 272 forks source link

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

Closed shearerpmm closed 1 year ago

shearerpmm commented 1 year ago

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(...)
haozhou1988 commented 1 year ago

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

francisbarton commented 1 year ago

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))

hadley commented 1 year ago

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