Combine select helpers and predicate function to mutate in dplyr

Aurèle

I'd like to programmatically select which columns to mutate, based on a predicate function (e.g. is.character), and a "select helper" (e.g. starts_with("Z")) at the same time.

library(dplyr)

df <- tibble(V1 = "a", V2 = 1, Z1 = "a", Z2 = 1)

Desired output (mutate_at(df, "Z1", paste, "b") but without selecting Z1 explicitely):

structure(list(V1 = "a", V2 = 1, Z1 = "a b", Z2 = 1), class = c(
  "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -1L))

In other words, how to "combine" mutate_at(df, vars(starts_with("Z")), paste, "b") and mutate_if(df, is.character, paste, "b") in a single mutate?

Aurèle

In newer versions of tidyselect and dplyr, we can use where to turn a predicate function into a select helper.

df %>% 
  mutate(across(where(is.character) & starts_with("Z"), paste, "b"))

#> # A tibble: 1 x 4
#>   V1       V2 Z1       Z2
#>   <chr> <dbl> <chr> <dbl>
#> 1 a         1 a b       1

We also have to use the newer across interface, since mutate_at is not compatible with where.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related