简体   繁体   English

根据 R 中数据框中的名称重命名列名

[英]Rename column names as per names in dataframe in R

Is there a way to rename column names in R as per values in Dataframe有没有办法根据 Dataframe 中的值重命名 R 中的列名

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_1 数据框,需要更改列名)

df
New_ColA   New_ColB
1           3
2           4

You can use match -您可以使用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 -或者在dplyr中使用rename_with的相同逻辑 -

library(dplyr)

df %>% rename_with(~df_1$Z[match(., df_1$D)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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