Home > Net >  move string at the end of column names to beginning
move string at the end of column names to beginning

Time:09-21

I have a counts data frame. The column names are A01_rep1, A02_rep1, A03_rep1, A01_rep2, A02_rep2 ..... I want to rename the column names to rep1_A01, rep1_A02, rep1_A03, rep2_A01, rep2_A02.....

I have tried using gsub but am confused how to accurately use it. Also used some iteration of this post counts matrix

CodePudding user response:

in base R:

names(data) <- sub("([^_] )_(.*)", "\\2_\\1", names(data))

In tidyverse:

data %>% 
   rename_with(~str_replace(., "([^_] )_(.*)", "\\2_\\1"))
  •  Tags:  
  • r
  • Related