Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort data by row

Tags:

sorting

r

I have a data frame like

Id  A B C D E F
a   1 2 9 4 7 6
b   4 5 1 3 6 10
c   1 6 0 3 4 5

I want a data frame like

Id
a  C E F D B A     #for a, C has the highest value, then E then F and so on...similarly for other rows
b  F E B A D C
c  B F E D A C

Basically, i am sorting each row of the data frame first and then replacing row values by the respective column names.

Is there any nice way to do this?

like image 617
user3664020 Avatar asked Apr 01 '26 00:04

user3664020


1 Answers

Use order with apply, extracting the names in the process, like this:

data.frame(
  mydf[1], 
  t(apply(mydf[-1], 1, function(x) 
    names(x)[order(x, decreasing = TRUE)])))
#   Id X1 X2 X3 X4 X5 X6
# 1  a  C  E  F  D  B  A
# 2  b  F  E  B  A  D  C
# 3  c  B  F  E  D  A  C

The result of apply needs to be transposed before it is recombined with the Id column.

like image 133
A5C1D2H2I1M1N2O1R2T1 Avatar answered Apr 03 '26 15:04

A5C1D2H2I1M1N2O1R2T1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!