-3

I have a dataframe with multiple years as variable headings with the format: Y_1998, Y_1999, etc up to 2018. Is there any way that I can rename all of these columns in a single line of code, instead of using the rename function for each variable?

WLR
  • 1
  • 2

1 Answers1

3

If your dplyr version is >=1.0.0 then you can use rename_with() and one of the select helpers (e.g. starts_with()) to match a pattern of column name.

library(tidyverse)

tibble(var1 = "a",
       Y_1999 = 1, Y_2000 = 0, Y_2001 = 1, Y_2002 = 0,
       some_other_var = "b") %>% 
  rename_with(.fn = ~ str_replace(.x, "Y_", "Year_"),
              .cols = starts_with("Y_"))