0

I have a data frame with 3 letter key column headings, which looks like:

MFB   MBB   WBB
 X     X     X 

and another data frame with the full names:

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

My question is, how would I go about renaming the columns so the original table looks like:

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

There are about 80 column headings I want to rename, so manually renaming each column is not desired. My guess is it could be done using a for loop or the 'map2' function from the 'purrr' library, but I am not sure where to start.

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
John Bacot
  • 31
  • 2

1 Answers1

0

Similar to Rename multiple columns given character vectors of column names and replacement

To make your question fully reproducible, let's start with

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"))

If the keys can be sorted in the same order as the original column headings, then a simple

setNames(sports,pairs$Descr)

works. Otherwise

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

pgcudahy
  • 1,542
  • 13
  • 36