This replaces each occurrence of all characters up to and including underscore with the empty string and then makes the result unique. We can optionally remove %>% make.unique
in the first case or %>% as_tibble(.name_repair = "unique")
in the second case if it is known that the names will be unique anyways.
library(dplyr)
DF %>% rename_all(~ sub(".*_", "", .x) %>% make.unique)
or this which disambiguates the names in a slightly different manner.
library(dplyr)
library(tibble)
DF %>% rename_all(~ sub(".*_", "", .x)) %>% as_tibble(.name_repair = "unique")
Example
For example, using the first case above add prefixes to each name of the built in anscombe
creating DF
and apply the above to that in the last line of code below.
# set up a test data frame using builtin anscombe
DF <- setNames(anscombe, sub("(.)(.)", "\\1_\\2", names(anscombe)))
names(DF)
## [1] "x_1" "x_2" "x_3" "x_4" "y_1" "y_2" "y_3" "y_4"
DF %>% rename_all(~ sub(".*_", "", .x) %>% make.unique)
## 1 2 3 4 1.1 2.1 3.1 4.1
## 1 10 10 10 8 8.04 9.14 7.46 6.58
## 2 8 8 8 8 6.95 8.14 6.77 5.76
## ...etc...
gsub
will help – Tushar Ladsubstring(x, 5)
should do. – zx8754