R rename multiple columns with wildcard with rename_with()

Viewed 730

library(tidyverse)

I am looking to rename bunch columns and I tried to use rename_at() or rename_with() in R but not much success, can someone help? Thank you very much for your help.

Original data frame column names

tibble(
AAA_BBB1_P1_Elev = as.double(),
AAA_BBB2_P2_Elev = as.double(),
AAA_BBB2_P3_Elev = as.double()
)

Want to change the column names to

tibble(
`BBB1-P1E` = as.double(),
`BBB1-P2E` = as.double(),
`BBB1-P3E` = as.double()
)

4 Answers

We can use rename_all with str_replace

library(dplyr)
library(stringr)
tbl2 <- tbl1 %>%
     rename_all(~ str_replace_all(str_replace(., '^[^_]+_(.*)_(.)[^.]+$', "\\1\\2"), '_', "-"))

-output

tbl2
# A tibble: 0 x 3
# … with 3 variables: `BBB1-P1E` <dbl>, `BBB2-P2E` <dbl>, `BBB2-P3E` <dbl>

data

tbl1 <- structure(list(AAA_BBB1_P1_Elev = numeric(0), AAA_BBB2_P2_Elev = numeric(0), 
    AAA_BBB2_P3_Elev = numeric(0)), row.names = integer(0), class = c("tbl_df", 
"tbl", "data.frame"))

Inspired by akrun's answer, I came up with a work-around...

remove <- c("AAA_BBB[0-9]_", "lev", "_") 

tibble(
AAA_BBB1_P1_Elev = as.double(), 
AAA_BBB2_P2_Elev = as.double(), 
AAA_BBB2_P3_Elev = as.double()
) %>% 
rename_all(~ str_remove_all(., paste(remove, collapse = "|"))) %>% 
rename_at(vars(ends_with("E")), ~ paste0("BBB1-", .x)) 

# A tibble: 0 x 3 
# ... with 3 variables: BBB1-P1E <dbl>, BBB1-P2E <dbl>, BBB1-P3E <dbl> 

Base R option :

names(df) <- sub('\\w+_(\\w+)_(\\w+)_.*', '\\1-\\2E', names(df))
names(df)
#"BBB1-P1E" "BBB2-P2E" "BBB2-P3E"

I had a similar problem. Data on people tested on two occasions was given as

Data %>%
  select(Identifier, contains('eq5d'),-EQ5D3L_Combined) %>%
  names()

which gave this list of names.

"Identifier" "EQ5D3L_Item_1" "EQ5D3L_Item_2"
"EQ5D3L_Item_3" "EQ5D3L_Item_4" "EQ5D3L_Item_5"
"EQ5D3L_VAS" "EQ5D3L_Item_1_2" "EQ5D3L_Item_2_2" "EQ5D3L_Item_3_2" "EQ5D3L_Item_4_2" "EQ5D3L_Item_5_2" "EQ5D3L_VAS_2"

The '_2' was the second measurement occasion, and I needed to put '_1' at the end of the variable from the first occasion.

To fix this I used rename_with as follows

Data %>%
   select(Identifier, contains('eq5d'),-EQ5D3L_Combined) %>% 
   rename_with(~ifelse(!str_ends(.x,'[0-9]'),
                       str_c(.x,'_1'),
                       .x)) %>%
    names()

The !str_end picks out variable names which did not end with a number, as a logical vector. The ifelse applies the rename_with only to those which did not end in a number, and the str_c adds '_1' to those - so I now have my variable named correctly for an easy pivot_longer.

Related