Reputation: 1870
Just like in title: is there any function that allows applying another function to column names of data frame
? I mean something like forcats::fct_relabel
that applies some function to factor labels.
To give an example, supose I have a data.frame
as below:
X<-data.frame(
firababst = c(1,1,1),
secababond = c(2,2,2),
thiababrd = c(3,3,3)
)
X
firababst secababond thiababrd
1 1 2 3
2 1 2 3
3 1 2 3
Now I wish to get rid of abab
from column names by applying stringr::str_remove
. My workaround involves magrittr::set_colnames
:
X %>%
set_colnames(colnames(.) %>% str_remove('abab'))
first second third
1 1 2 3
2 1 2 3
3 1 2 3
Can you suggest some more strightforward way? Ideally, something like:
X %>%
magic_foo(str_remove, 'abab')
Upvotes: 2
Views: 335
Reputation: 40171
You can do:
X %>%
rename_all(~ str_remove(., "abab"))
first second third
1 1 2 3
2 1 2 3
3 1 2 3
Upvotes: 1