mike ropri
mike ropri

Reputation: 27

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

Upvotes: 0

Views: 204

Answers (1)

Onyambu
Onyambu

Reputation: 79228

in base R:

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

In tidyverse:

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

Upvotes: 2

Related Questions