Home > Blockchain >  Rename vars with numeric names
Rename vars with numeric names

Time:11-23

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.

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.

CodePudding user response:

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
  • Related