Remake plyr::rename(warn_missing = FALSE) using dplyr verbs

How one can remake the plyr::rename(warn_missing = FALSE) behavior using dplyr (tidyverse) verbs?

library(tidyverse)

namekey <- c(
  mpg = "miles_per_gallon",
  dist = "distance"
)

mtcars %>% head(1)
#>           mpg cyl disp  hp drat   wt  qsec vs am gear carb
#> Mazda RX4  21   6  160 110  3.9 2.62 16.46  0  1    4    4

mtcars %>% head(1) %>%
  plyr::rename(replace = namekey, warn_missing = FALSE)
#>           miles_per_gallon cyl disp  hp drat   wt  qsec vs am gear carb
#> Mazda RX4               21   6  160 110  3.9 2.62 16.46  0  1    4    4

Goal: to rename many columns (using a dictionary), but silently ignoring the missing columns.
Rationale: to create/test only one common dictionary, not a large number of slightly overlapping dictionaries.

1 Like

Try:

library(tidyverse)

namekey <- c(
  "miles_per_gallon" = "mpg",
  "distance" = "dist"
)

mtcars %>% head(1) %>%
  dplyr::rename(any_of(namekey))
#>           miles_per_gallon cyl disp  hp drat   wt  qsec vs am gear carb
#> Mazda RX4               21   6  160 110  3.9 2.62 16.46  0  1    4    4

Created on 2021-04-01 by the reprex package (v1.0.0)

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.