Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

move string at the end of column names to beginning

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 Move characters from beginning of column name to end of column name (additonal question) but have not found it to work. Any help is appreciated.

counts matrix

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

in base R:

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

In tidyverse:

data %>% 
   rename_with(~str_replace(., "([^_]+)_(.*)", "\\2_\\1"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading