I wrote the following (working) function to change column names from vectors that contain both the current and desired column names,
change.name <- function (dt, from, to)
{
loc <- match(from, names(dt))
chg.loc <- loc[!is.na(loc)]
if (length(chg.loc) == 0)
return(dt)
names(dt)[chg.loc] = to[!is.na(loc)]
return(dt)
}
Is it possible to replace this function with rename or some other part of dplyr. I would rather not need my own function.
Here is an example of the desired functionality,
cnames = tibble(from = c("hair_color", "banana", "height"),
to = c("HeadCap", "Orange", "VertMetric"))
starwars %>% select(name, height, mass, hair_color, skin_color) %>%
top_n(5) %>% change.name(cnames$from, cnames$to)
name VertMetric mass HeadCap skin_color <chr> <int> <dbl> <chr> <chr> 1 R2-D2 96 32 NA white, blue 2 R5-D4 97 32 NA white, red 3 Gasgano 122 NA none white, blue 4 Luminara Unduli 170 56.2 black yellow 5 Barriss Offee 166 50 black yellow
Note that "banana" in cnames$from is missing from starwars and doesn't trip up the function.