I would like to remove all but the final instance of an underscore _ from variable names in a data frame.
For example, my current data frame looks like this:
structure(list(subjectID = c("P1", "P2", "P3", "P4", "P5"), var_t1_new_3m = c(1,
3, 5, 2, 1), var_t1_old_3m = c(6, 8, 9, 2, 3), var_t2_new_6m = c(1,
5, 8, 9, 3), var_t2_old_6m = c(5, 3, 8, 1, 7), var_t3_new_12m = c(1,
9, 2, 7, 3), var_t3_old_12m = c(6, 1, 4, 9, 3)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -5L))
And I would like the variable names to look like this:
structure(list(subjectID = c("P1", "P2", "P3", "P4", "P5"), vart1new_3m = c(1,
3, 5, 2, 1), vart1old_3m = c(6, 8, 9, 2, 3), vart2new_6m = c(1,
5, 8, 9, 3), vart2old_6m = c(5, 3, 8, 1, 7), var3new_12m = c(1,
9, 2, 7, 3), var3old_12m = c(6, 1, 4, 9, 3)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -5L))
I tried to use a solution from a previous post (How to remove all occurrences of an underscore before a pattern?) using str_replace to see if it would do the trick:
x <- c("age_eeg_3m, age_eeg_6m, age_eeg_12m")
str_replace_all(x, "(.*)(?=_[:digit:]m)", (x) str_remove_all(x, fixed("_")))
which resulted in…
[1] "ageeeg3m, ageeeg_6m, age_eeg_12m"
It worked for the first two elements, but not for the last one where there are two digits in between the final _ and ‘m’.
Ideally, I would like to avoid using the characters after the final _ as a “pattern” (i.e., _3m / _6m ? 12m). This way I could apply the code to any variable name that has multiple underscores.
Replace underscore followed by non-underscore characters and then end of string ($) with itself. Now once that is consumed it won’t be scanned again so we can replace the alternative which is just underscore with the capture group which is now empty.
library(dplyr)
dat %>% setNames(gsub("(_[^_]*)$|_", "\1", names(.)))
giving
# A tibble: 5 × 7
subjectID vart1new_3m vart1old_3m vart2new_6m vart2old_6m vart3new_12m vart3old_12m
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 P1 1 6 1 5 1 6
2 P2 3 8 5 3 9 1
3 P3 5 9 8 8 2 4
4 P4 2 2 9 1 7 9
5 P5 1 3 3 7 3 3
Would this work?
names(df) <- gsub("_(?=.*_)", "", names(df), perl = TRUE)
cat(names(df), sep = "n")
# subjectID
# vart1new_3m
# vart1old_3m
# vart2new_6m
# vart2old_6m
# vart3new_12m
# vart3old_12m
Data
df <- data.frame(
subjectID = character(0),
var_t1_new_3m = numeric(0),
var_t1_old_3m = numeric(0),
var_t2_new_6m = numeric(0),
var_t2_old_6m = numeric(0),
var_t3_new_12m = numeric(0),
var_t3_old_12m = numeric(0)
)