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

sort colum name with character and number

I have this df:

table
              C1 C10 C11 C12 C13 C14 C15 C16 C17 C18 C2 C3 C4 C5 C6 C7 C8 C9
Mest           1   1   1   1   0   0   0   0   0   0  0  0  0  0  0  0  0  0
Dlk1           0   0   0   0   0   0   0   0   0   0  0  0  1  0  0  0  0  0
Meg3           0   0   0   0   0   0   0   0   0   0  0  0  0  0  0  0  0  0

I’d like to order the columns, I’ve tried:

colnames(table) <- stringr::str_sort(colnames(table),numeric = TRUE) 

but It only changes the name of columns in alphabetic order leaving the column in the same position:

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

table
               C1  C2  C3 C4  C5  C6  C7  C8  C9 C10 C11 C12 C13 C14 C15 C16 C17 C18
Mest           1   1   1   1   0   0   0   0   0   0   0   0   0   0   0  0   0   0
Dlk1           0   0   0   0   0   0   0   0   0   0   0   0   1   0   0  0   0   0
Meg3           0   0   0   0   0   0   0   0   0   0   0   0   0   0   0  0   0   0

>Solution :

Base R,

DAT[,order(as.integer(sub("\\D", "", names(DAT))))]
#      C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 C11 C12 C13 C14 C15 C16 C17 C18
# Mest  1  0  0  0  0  0  0  0  0   1   1   1   0   0   0   0   0   0
# Dlk1  0  0  0  1  0  0  0  0  0   0   0   0   0   0   0   0   0   0
# Meg3  0  0  0  0  0  0  0  0  0   0   0   0   0   0   0   0   0   0
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