Łukasz Deryło
Łukasz Deryło

Reputation: 1870

How to apply function to colnames in tidyverse

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

Answers (2)

akrun
akrun

Reputation: 887941

With base R, we can do

names(X) <- sub("abab", "", names(X))

Upvotes: 0

tmfmnk
tmfmnk

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

Related Questions