I have the dataframe below which will actually have a dynamic number of columns.I want to paste a string "-actual" from the second column name up to the last column name of the dataframe.
structure(list(month = c("Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), `2020` = c(NA, 5.26666666666667,
-15.5806451612903, -41.4333333333333, -27.1290322580645, -15.7666666666667,
-14.8709677419355, -14.9677419354839, -14.9333333333333, -15.7741935483871,
-19.8666666666667, -19.741935483871), `2021` = c(-25.5806451612903,
-23.4285714285714, -10.8387096774194, -8.3, -5.41935483870968,
-3.53333333333333, -3.87096774193548, -4.67741935483871, -6.1,
-5.54838709677419, -7.43333333333333, -6.7741935483871), `2022` = c(-18.9677419354839,
-12.3571428571429, -10.4193548387097, -8.66666666666667, -6.06451612903226,
-6.83333333333333, -8.64516129032258, -7.09677419354839, -8.73333333333333,
-8.53333333333333, NA, NA)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -12L))
>Solution :
Using dplyr::rename_with():
library(dplyr)
df %>%
rename_with(\(x) paste0(x, "-actual"), .cols = !month)
# A tibble: 12 × 4
month `2020-actual` `2021-actual` `2022-actual`
<chr> <dbl> <dbl> <dbl>
1 Jan NA -25.6 -19.0
2 Feb 5.27 -23.4 -12.4
3 Mar -15.6 -10.8 -10.4
4 Apr -41.4 -8.3 -8.67
5 May -27.1 -5.42 -6.06
6 Jun -15.8 -3.53 -6.83
7 Jul -14.9 -3.87 -8.65
8 Aug -15.0 -4.68 -7.10
9 Sep -14.9 -6.1 -8.73
10 Oct -15.8 -5.55 -8.53
11 Nov -19.9 -7.43 NA
12 Dec -19.7 -6.77 NA
NB, since the cols argument uses the tidyselect DSL, you can get the same result using:
!month(all columns besides"month"),`2020`:`2022`(all columns from"2020"through"2022"),matches("^\\d+$")(all columns consisting of digits only), orwhere(is.numeric)(all columns with numeric values)