Z. Zhang
Z. Zhang

Reputation: 757

Rename dataframe column names by switching string patterns

I have following dataframe and I want to rename the column names to c("WBC_MIN_D7", "WBC_MAX_D7", "DBP_MIN_D3")

> dataf <- data.frame(
+     WBC_D7_MIN=1:4,WBC_D7_MAX=1:4,DBP_D3_MIN=1:4
+ )
> dataf
  WBC_D7_MIN WBC_D7_MAX DBP_D3_MIN
1          1          1          1
2          2          2          2
3          3          3          3
4          4          4          4
> names(dataf)
[1] "WBC_D7_MIN" "WBC_D7_MAX" "DBP_D3_MIN"

Probably, the rename_with function in tidyverse can do it, But I cannot figure out how to do it.

Upvotes: 2

Views: 61

Answers (2)

pbraeutigm
pbraeutigm

Reputation: 723

You can rename your dataf with your vector with names(yourDF) <- c("A","B",...,"Z"):

names(dataf) <- c("WBC_MIN_D7", "WBC_MAX_D7", "DBP_MIN_D3")

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388862

You can use capture groups with sub to extract values in order -

names(dataf) <- sub('^(\\w+)_(\\w+)_(\\w+)$', '\\1_\\3_\\2', names(dataf))

Same regex can be used in rename_with -

library(dplyr)

dataf %>% rename_with(~ sub('^(\\w+)_(\\w+)_(\\w+)$', '\\1_\\3_\\2', .))

#  WBC_MIN_D7 WBC_MAX_D7 DBP_MIN_D3
#1          1          1          1
#2          2          2          2
#3          3          3          3
#4          4          4          4

Upvotes: 3

Related Questions