Home > Net >  How to order data frame columns alphabetically and numerically in R?
How to order data frame columns alphabetically and numerically in R?

Time:04-29

I have the following df:

A1 <- c(1,2,5)
B1 <- c(6,2,4)
C1 <- c(4,1,3)
A2 <- c(3,8,9)
B2 <- c(1,2,3)
C2 <- c(2,6,9)

df_1 <- data.frame(A1,A2,B1,B2,C1,C2)

How can I reorder the columns as I have below?

df_2 <- data.frame(A1,B1,C1,A2,B2,C2)

CodePudding user response:

We may use parse_number to extract the names and order

library(dplyr)
df1_1 <- df_1 %>% 
   select(order(readr::parse_number(names(.)), names(.))

-output

  A1 B1 C1 A2 B2 C2
1  1  6  4  3  1  2
2  2  2  1  8  2  6
3  5  4  3  9  3  9

Or using base R - get the numeric part with sub, and order separately the numeric first

df_1[order(as.integer(sub("\\D ", "", names(df_1))), names(df_1))]
  A1 B1 C1 A2 B2 C2
1  1  6  4  3  1  2
2  2  2  1  8  2  6
3  5  4  3  9  3  9
  • Related