Let me create an example first and then explain the question:
old_names <- c("FG%", "Dist.", "2P", "0-3", "3-10", "10-16")
new_names <- c("FG%", "Dist", "2P_Freq", "0_3_Freq", "3_10_Freq", "10_16_Freq")
dput(mydf)
structure(list(`FG%` = c(0.451, 0.454, 0.444, 0.444, 0.442),
`2P` = c(0.691, 0.607, 0.629, 0.744, 0.665), `0-3` = c(0.331,
0.296, 0.309, 0.28, 0.282), `10-16` = c(0.092, 0.071, 0.077,
0.117, 0.099)), row.names = c(NA, 5L), class = "data.frame")
mydf
FG% 2P 0-3 10-16
1 0.451 0.691 0.331 0.092
2 0.454 0.607 0.296 0.071
3 0.444 0.629 0.309 0.077
4 0.444 0.744 0.280 0.117
5 0.442 0.665 0.282 0.099
I have a dataframe mydf
that has a varying number of columns. I am aware of the entire possible set of current column names old_names
, and when they are present in the dataframe, I would like to replace them with the value at the same index in new_names
. In the example above, 4 of the 6 columns are present, and I need them renamed to the new_names values.
A solution that uses one or more of dplyr's rename, rename_at, rename_if, rename_all would be particularly useful, as I try to use dplyr as much as I can for this type of data manip. I have tried a few attempts on this with no luck.
Any help on this would be greatly appreciated!