简体   繁体   中英

Renaming multiple similar column names

I have a data frame that has columns ranging from start_1 to start_32. I'd like to rename all of them to m1 to m32. So far I have done this using the following code:

df %>%
  rename(m1 = start_1,
         m2 = start_2,
         ...
         m32 = start_32)

I may need to do this a few more times for other variables and I am looking for more condensed way of achieving the same goal. Thanks!

You can use names :

names(df) <- gsub("^start_", "m", names(df))

or, in dplyr , with rename_with :

library(dplyr)
rename_with(df, ~ gsub("start_", "m", .x), starts_with("start_"))
rename_with(df, ~ gsub("^start_", "m", .x))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM