How do I add a prefix to several variable names using dplyr?

The latest solution (2020) seems to use rename_with, which is available in dplyr 1.0.0 and higher:

mtcars %>% rename_with(.fn = ~ paste0("Myprefix_", .x, "_Mypostfix")) -> mtcars.custom

Use the .cols = argument to specify a subset of variables, it defaults to everything().


Indeed, you can use rename_ (NSE rename itself doesn’t work):

data %>% rename_(.dots = setNames(names(.), paste0('cars.', names(.))))

… but honestly, why? Just assigning names directly is shorter and more readable:

data %>% setNames(paste0('cars.', names(.)))

Tags:

R

Dplyr