Is there a way to rename column names in R as per values in Dataframe
df
ColA ColB
1 3
2 4
These above column names should be renamed. But I have these in another dataframe below
df_1
D Z
ColA New_ColA
ColB New_ColB
Expected output (so with reference to df_1 dataframe, the column names needs to be changed)
df
New_ColA New_ColB
1 3
2 4
You can use match
-
names(df) <- df_1$Z[match(names(df), df_1$D)]
df
# New_ColA New_ColB
#1 1 3
#2 2 4
Or the same logic using rename_with
in dplyr
-
library(dplyr)
df %>% rename_with(~df_1$Z[match(., df_1$D)])
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.