Home > Net >  How to rename a column with dplyr?
How to rename a column with dplyr?

Time:01-26

I'm trying to use dplyr's rename function but my column names are variable and I would like to use a function to set the column name and it's not working.

My code:

library(dplyr)

data_hoje <- as.Date("2023-01-20")

teste %>%
  rename("Há 30 dias" = V1,
         "Há 7 dias" = V2,
         paste0(format(data_hoje, "%d/%b/%y")) = V3,
         " " = Delta)

I'm getting this error:

Error: unexpected '=' in: " "Há 7 dias" = V2, paste0(format(data_hoje, "%d/%b/%y")) ="

My dput:

structure(list(V1 = c("2022-12-20", "5.1908", "3.6700", "3.3729", 
"3.3400", NA, "5.2205"), V2 = c("2023-01-13", "5.3720", "3.8095", 
"3.4606", "3.3997", "3.2951", "5.3589"), V3 = c("2023-01-20", 
"5.4573", "3.8953", "3.5577", "3.5023", "3.5357", "5.4372"), 
    Delta = c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE)), class = "data.frame", row.names = c("Data", 
"2023", "2024", "2025", "2026", "2027", "Suavizada"))

How can I make this code work?

CodePudding user response:

Use this:

teste %>% rename("Há 30 dias" := V1,
         "Há 7 dias" := V2,
         "{paste0(format(data_hoje, '%d/%b/%y'))}" := V3,
         " " := Delta)

see vignette("programming")

  • Related