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:
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