Column names when using funs() in mutate_all()

In the following code, the new column names are name1_log and name2_log. Is there an additional argument specifying whether to append "log" at the end or at the start of the old column names? (I would prefer it to be at the start)

tibble(name1 = 2:4, name2 = 3:5) %>% mutate_all(funs(log = log(.)))

1 Like

There is not sorry. Unfortunately fully parameterising all the ways you might want to create names would make mutate_all() very complicated.

2 Likes

You could fix the names after the fact, e.g. with purrr::set_names, which can take a function to apply to the names:

library(tidyverse)

tibble(name1 = 2:4, name2 = 3:5) %>% 
    mutate_all(funs(log = log)) %>% 
    set_names(~gsub('(.*)_log', 'log_\\1', .x))
#> # A tibble: 3 x 4
#>   name1 name2 log_name1 log_name2
#>   <int> <int>     <dbl>     <dbl>
#> 1     2     3 0.6931472  1.098612
#> 2     3     4 1.0986123  1.386294
#> 3     4     5 1.3862944  1.609438

You can use dplyr::rename_all in a similar manner, or rename_at, which allows you to avoid regex and keep it all within dplyr:

library(dplyr)

tibble(name1 = 2:4, 
       name2 = 3:5) %>% 
    mutate_all(funs(log = log(.))) %>% 
    rename_at(vars(ends_with('_log')), 
              funs(paste0('log_', 
                          substr(., 1, nchar(.) - 4))))
#> # A tibble: 3 x 4
#>   name1 name2 log_name1 log_name2
#>   <int> <int>     <dbl>     <dbl>
#> 1     2     3 0.6931472  1.098612
#> 2     3     4 1.0986123  1.386294
#> 3     4     5 1.3862944  1.609438
8 Likes