Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rename vars with numeric names

Say I have a dataframe with variables that have numeric names that I want to rename by adding character prefixes.

country <- c("country","US","France")
var1  <- c(234234,234234,1233124)
var2  <- c(34534,25674,123124)

df <- data.frame(country,var1,var2) %>% rename('2021' = var1,'2022' = var2)
Country 2021 2022
country 234234 34534
US 234234 25674
France 1233124 123124

Example table is weird, sorry. My attempt using rename_if:

df_clean <- df %>%
  rename_if(startsWith(names(.),"20"), ~paste0("ben",.))

I get variable names that have quotes around the years.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Country ben’2021′ ben’2022′
country 234234 34534
US 234234 25674
France 1233124 123124

I want:

Country ben2021 ben2022
country 234234 34534
US 234234 25674
France 1233124 123124

I’d appreciate any help with the rename. Sorry if formatting isn’t right and if I missed the answer in my search.

>Solution :

Using rename_with instead of the superseded rename_if you could do:

library(dplyr, warn = FALSE)

df_clean <- df %>%
  rename_with(~ paste0("ben", .), starts_with("20"))

df_clean
#>   country ben2021 ben2022
#> 1 country  234234   34534
#> 2      US  234234   25674
#> 3  France 1233124  123124
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading