使用键更改列名

时间:2019-12-13 04:38:52

标签: r rename purrr

我有一个带有3个字母键列标题的数据框,如下所示:

MFB   MBB   WBB
 X     X     X 

和另一个全名的数据框:

Key   Descr
MFB   Men's Football
MBB   Men's Basketball
WBB   Women's Basketball

我的问题是,我将如何重命名列,以便原始表看起来像这样:

Men's Football   Men's Basketball   Women's Basketball
       X                X                   X 

我要重命名大约80个列标题,因此不需要手动重命名每个列。我的猜测是可以使用for循环或“ purrr”库中的“ map2”函数来完成此操作,但我不确定从哪里开始。

1 个答案:

答案 0 :(得分:0)

类似于Rename multiple columns given character vectors of column names and replacement

为了使您的问题完全可重复,让我们开始

library(tidyverse)
sports <- tibble(MFB=c("bears", "texans", "packers"), 
    MBB=c("bulls", "heat", "bucks"), 
    WBB=c("dream", "sky", "sun"))

pairs <- tibble(Key=c("MFB", "MBB", "WBB"), 
    Descr=c("Men's Football", "Men's Basketball", "Women's Basketball"))

如果可以按照与原始列标题相同的顺序对键进行排序,那么简单的

setNames(sports,pairs$Descr)

有效。否则

sports %>% rename_at(pairs$Key, ~pairs$Descr)