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()
)
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>
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With