I have a table with column names that I want to change based on a table with a column of the current names and a column of the replacement names.
As an example:
library(tidyverse)
name_tbl <- enframe(names(mtcars), value = "old_names") %>%
rowwise() %>%
mutate(new_names = paste0(old_names, sample(50:100, 1)))
name_tbl
#> # A tibble: 11 x 3
#> # Rowwise:
#> name old_names new_names
#> <int> <chr> <chr>
#> 1 1 mpg mpg79
#> 2 2 cyl cyl57
#> 3 3 disp disp70
#> 4 4 hp hp57
#> 5 5 drat drat72
#> 6 6 wt wt88
#> 7 7 qsec qsec86
#> 8 8 vs vs66
#> 9 9 am am91
#> 10 10 gear gear71
#> 11 11 carb carb50
At this point, I would like to be able to do something like:
mtcars %>% rename(name_tbl$old_names = name_tbl$new_names)
however it of course does not work because rename expects named arguments.
I've looked all over and have not found a tidyverse method of doing this operation. Is there some way to rename columns using a lookup table like this?
Currently I'm pivoting longer on everything and then left_joining the key table, however this is problematic because all columns have to be converted to the same type first, which is not easily undone.