The newest dplyr version became more flexible by adding rename_with()
where _with
refers to a function as input. The trick is to reformulate the character vector newnames
into a formula (by ~
), so it would be equivalent to function(x) return (newnames)
.
In my subjective opinion, that is the most elegant dplyr expression.
# shortest & most elegant expression
df %>% rename_with(~ newnames, oldnames)
A w B
1 1 2 3
If you reverse the order, argument .fn must be specified as .fn is expected before .cols argument.
df %>% rename_with(oldnames, .fn = ~ newnames)
A w B
1 1 2 3