Siddharth Sharma Siddharth Sharma - 3 months ago 10
R Question

How to sort entire dataframe by one row's content

I have a dataframe as follows:

Col1 Col2 Col3 Col4 Col5

1794.7809 336.5778 0.2233495 0.53030000 5594.83998270378
28.7967 16.0021 2.6449000 81.8828 g
31.6036 11.7235 2.5185000 0.53030000 g
162.0520 136.0310 4.0612000 0.03740000 g
23.8172 9.5728 2.3385000 0.61470000 g


I would like to sort the entire dataframe based on the values in the first row (namely : 1794.7809 336.5778 0.2233495 0.53030000 5594.83998270378) such that not only this row is sorted but all rows corresponding to these values are also arranged properly. Any help would be much appreciated.

Edit:
The output should be as follows:

Col3 Col4 Col2 Col1 Col5

0.2233495 0.53030000 336.5778 1794.7809 5594.83998270378
2.6449000 81.8828 16.0021 28.7967 g
2.5185000 0.53030000 11.7235 31.6036 g
4.0612000 0.03740000 136.0310 162.0520 g
2.3385000 0.61470000 9.5728 23.8172 g


(Note : Search on google for this issue was fruitless)
(Note : Part of an assignment)
Regards

Answer

Assuming there is no factor variable in your original data frame, you can use order on the first row, which

returns a permutation which rearranges its first argument into ascending or descending order

and apply the result on the data frame:

df[order(as.numeric(unlist(df[1,])))]

#        Col3    Col4     Col2      Col1             Col5
# 1 0.2233495  0.5303 336.5778 1794.7809 5594.83998270378
# 2 2.6449000 81.8828  16.0021   28.7967                g
# 3 2.5185000  0.5303  11.7235   31.6036                g
# 4 4.0612000  0.0374 136.0310  162.0520                g
# 5 2.3385000  0.6147   9.5728   23.8172                g

Converting factor variable to character should be fairly straight forward with the mutate_if function from dplyr:

df %>% mutate_if(is.factor, as.character)