Jake
Jake

Reputation: 95

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))]

Upvotes: 0

Views: 39

Answers (1)

JasonWang
JasonWang

Reputation: 2434

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

As you mentioned in the comment, this solution will still work if you can accept the order of price and stock is not consistent. Here is an example:

# Example
df

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

# Solution
# Note that the order of stock and price is not consistent
df[, c(1, order(as.numeric(gsub("[^0-9]+", "", names(df)[-1]))) + 1)]

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

Here is a way to work around that:

df1 <- df[c(names(df)[1], sort(names(df)[-1], decreasing=TRUE))]
df1[, c(1, order(as.numeric(gsub("[^0-9]+", "", names(df1)[-1]))) + 1)]

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

Upvotes: 2

Related Questions