I'm trying to rename several columns in a list of tibbles
based on regex.
Let's take a look on the following example:
library(tidyverse)
df1 <- tibble(
id_site = 1,
country = rep(paste0("country", 1:2), each = 3, len = 5),
species = rep(paste0("sp.", c(1, 3)), each = 3, len = 5),
min = c(100, 900, 2200, 400, 1300)
)
df2 <- tibble(
id_ref = 2,
country = "country3",
species = rep(paste0("sp.", 2:6), each = 1, len = 4),
min_alt = c(2700, 400, 600, 1800)
)
I would like to rename id_site
to id_ref
in df1
and min_alt
to min
in df2
.
I manage to rename one column at a time using the following code:
list(df1, df2) %>%
set_names("df1", "df2") %>%
map(
~ .x %>%
rename_at(
colnames(.) %>% str_which("alt$"),
~ .x %>% str_replace(".+", "min")
) %>%
rename_at(
colnames(.) %>% str_which("site$"),
~ .x %>% str_replace(".+", "id_ref")
)
)
but I find it quite repetitive…
I'd like to know if it's possible to do this in one go within a single rename_x
function.