rename all columns in list of data frames

Viewed 120

I have a list of dataframes

vars <- c("Col_1", "Col_2", "Col_3")

list_df <- list(
  tibble(
    a = 1,
    b = 2,
    c = 3
  ),
  tibble (
    d = 1,
    e = 2,
    f = 3
  )
)

And I'd like to rename the columns using the vars but I think I'm missing something here.

map(list_df, ~rename_all(.x, vars))

The result should be:

list(
  tibble(
    Col_1 = 1,
    Col_2 = 2,
    Col_3 = 3
  ),
  tibble (
    Col_1 = 1,
    Col_2 = 2,
    Col_3 = 3
  )
)

I'd like this to work regardless of the initial column names (and all data frames will always only have three columns. Is this possible?

2 Answers

We need the ~ inside the rename_all

library(purrr)
library(dplyr)
map(list_df, ~rename_all(.x, ~ vars))
#[[1]]
# A tibble: 1 x 3
#  Col_1 Col_2 Col_3
#  <dbl> <dbl> <dbl>
#1     1     2     3

#[[2]]
# A tibble: 1 x 3
#  Col_1 Col_2 Col_3
#  <dbl> <dbl> <dbl>
#1     1     2     3

Or with set_names/setNames

map(list_df, set_names, vars)
map(list_df, setNames, vars)

Here is a base R solution

Map(setNames,list_df,list(vars))

which gives

> Map(setNames,list_df,list(vars))
[[1]]
# A tibble: 1 x 3
  Col_1 Col_2 Col_3
  <dbl> <dbl> <dbl>
1     1     2     3

[[2]]
# A tibble: 1 x 3
  Col_1 Col_2 Col_3
  <dbl> <dbl> <dbl>
1     1     2     3
Related