1

If I had a dataframe:

df <- tribble(
~col_A_new, ~col_B_old, ~var_A_new, ~var_B_old, ~ID,
1, 2, 3, 4, "A",
2, 3, NA, 4, "B",
3, NA, NA, NA, "C",
4, NA, NA, 5, "D")

A tibble: 4 × 5
  col_A_new col_B_old var_A_new var_B_old ID   
      <dbl>     <dbl>     <dbl>     <dbl> <chr>
1         1         2         3         4 A    
2         2         3        NA         4 B    
3         3        NA        NA        NA C    
4         4        NA        NA         5 D    

And I wanted to rename the columns starting with "col" or "var" using two functions so that everything was lower case and all underscores were removed, I could do the following long way...

df %>%
    rename_with(.fn = ~str_to_lower(.), .cols = starts_with(c('col', 'var'))) %>% 
    rename_with(.fn = ~str_remove_all(., "_"), .cols = starts_with(c('col', 'var')))

And end up with the desired output...

colanew colbold varanew varbold ID   
    <dbl>   <dbl>   <dbl>   <dbl> <chr>
1       1       2       3       4 A    
2       2       3      NA       4 B    
3       3      NA      NA      NA C    
4       4      NA      NA       5 D    

Is there a way to pass multiple functions to rename with to save me repeating this code each time I want to apply a different renaming function?

I would have thought something like this would work...

df %>%
    rename_with(.fn = list(
                           ~str_to_lower(.), 
                           ~str_remove_all(., "_")
                           ), 
                .cols = starts_with(c('col', 'var')))

But it doesn't!

stefan
  • 90,330
  • 6
  • 25
  • 51
Tom
  • 279
  • 1
  • 12

1 Answers1

2

You could do:

library(stringr)
library(dplyr)

df %>%
  rename_with(.fn = ~str_to_lower(.) %>% str_remove_all("_"), .cols = starts_with(c('col', 'var')))
#> # A tibble: 4 × 5
#>   colanew colbold varanew varbold ID   
#>     <dbl>   <dbl>   <dbl>   <dbl> <chr>
#> 1       1       2       3       4 A    
#> 2       2       3      NA       4 B    
#> 3       3      NA      NA      NA C    
#> 4       4      NA      NA       5 D
stefan
  • 90,330
  • 6
  • 25
  • 51