Jake Jake - 16 days ago 6
R Question

Sort a data frame and keep the main col

I have a dataframe like this

name stock_11 stock_1 stock_2
main1 0 4 1
main2 2 2 3
main3 4 4 8
main4 7 7 3


And I would like to short the df based on the name of every column but keep first the column "name". For the other col names it is column "stock_"

The output result I try to have is this:

name stock_1 stock_2 stock_11
main1 4 1 0
main2 2 3 2
main3 4 8 4
main4 7 3 7


I tried this but it sorts all names:

df[ , order(names(df))]

Answer

If you have a lot of columns

df[, c(1, order(as.numeric(gsub("[^0-9]+", "", names(df)[-1]))) + 1)]

   name stock_1 stock_2 stock_11
1 main1       4       1        0
2 main2       2       3        2
3 main3       4       8        4
4 main4       7       3        7
Comments