Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R rename multiple columns with wildcard with rename_with()

Tags:

r

rename

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()
)

like image 664
Nick Avatar asked Nov 20 '25 07:11

Nick


1 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"))
like image 50
akrun Avatar answered Nov 21 '25 20:11

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!