Search code examples
rfunctiondate

How to rename multiple columns names with format date?


I'd like to create a rename_col_df() function that renames all the columns in a data.frame except the first one (CODE_S).

Here's an example to reproduce the problem:

df <- data.frame(
  CODE_S = c(1, 2, 3),
  COL2 = c(10, 20, 30),
  COL3 = c(15, 25, 35)
)
colnames(df) <- c("CODE_S", "01/10/2023", "01/11/2023")

In this example, I only have 2 date columns, but in the real use case I have dozens of them.

Expected result: columns named "CODE_S", "2023-10-01", "2023-11-01".

I was thinking of using something like this but I can't get it into a function:

names(df) <- c("CODE_S",format(as.Date("01/11/2023", format = "%d/%m/%Y"), "%Y-%m-%d"))

Solution

  • One way using your idea and rename_with:

    library(dplyr)
    df |> 
      rename_with(~format(as.Date(., format = "%d/%m/%Y"), "%Y-%m-%d"), -"CODE_S")
    

    Output

      CODE_S 2023-10-01 2023-11-01
    1      1         10         15
    2      2         20         25
    3      3         30         35