Rename Columns using Vector of Names

You can use setNames() (base) or set_names()(purrr):

v = c('s_length', 's_width',' p_length', 'p_width', 'species')

iris |>
  setNames(v) |>
  head()
#>   s_length s_width  p_length p_width species
#> 1      5.1     3.5       1.4     0.2  setosa
#> 2      4.9     3.0       1.4     0.2  setosa
#> 3      4.7     3.2       1.3     0.2  setosa
#> 4      4.6     3.1       1.5     0.2  setosa
#> 5      5.0     3.6       1.4     0.2  setosa
#> 6      5.4     3.9       1.7     0.4  setosa

Created on 2024-02-02 with reprex v2.0.2

You can do that with an anonymous function:

v = c('s_length', 's_width',' p_length', 'p_width', 'species')

iris |>
  (\(.x) {colnames(.x) <- v; .x})() |>
  head()
#>   s_length s_width  p_length p_width species
#> 1      5.1     3.5       1.4     0.2  setosa
#> 2      4.9     3.0       1.4     0.2  setosa
#> 3      4.7     3.2       1.3     0.2  setosa
#> 4      4.6     3.1       1.5     0.2  setosa
#> 5      5.0     3.6       1.4     0.2  setosa
#> 6      5.4     3.9       1.7     0.4  setosa

Created on 2024-02-02 with reprex v2.0.2

That seems a lot harder, and also unreadable of course.

Actually I am tempted to ask about the context: if you need to rename all these columns based on an external vector, maybe you're asking the wrong questions (of course I have no idea in your particular case). Maybe these 120 columns should have been rows, and the right approach would be to pivot_longer() before renaming anything. Maybe you're reading it from a csv file with bad names, and the column renaming step should be part of a readr call. Maybe you should really modify the existing names with rename_with() rather than replace them all at once.

Or maybe I'm just wasting time thinking too much about a trivial problem :slight_smile:

1 Like