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?
Asked
Active
Viewed 3,510 times
-2
-
1You can assign a vector to the names of your ```data.frame()``` – fabla Feb 11 '21 at 13:30
-
1`names(data) <- sub("Y_", "Year_", names(data))` Please read the information at the top of the [tag:r] tag page on providing a complete reproducible example. – G. Grothendieck Feb 11 '21 at 13:32
1 Answers
7
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_"))

c_j_fairfield
- 198
- 6