Junitar
Junitar

Reputation: 999

Renaming different columns in a list of tibbles using purrr

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.

Upvotes: 2

Views: 788

Answers (2)

Cettt
Cettt

Reputation: 11981

here is one possibility:

list(df1, df2) %>% 
  set_names("df1", "df2") %>% 
  map(~rename_at(.x, vars(matches("^min")), ~"min")) %>%
  map(~rename_at(.x, vars(matches("id_site")), ~"id_ref"))

Upvotes: 3

kath
kath

Reputation: 7734

The following is a little bit less repetitive:

list(df1, df2) %>% 
  set_names("df1", "df2") %>% 
  map(~ .x %>% 
        rename_at(vars(matches("(alt|site)$")), 
                  str_replace_all, pattern = c("_alt" = "", "site" = "ref")))

Upvotes: 6

Related Questions