Sorting data by row

I have a dataframe 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 need 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 first sort each row of the dataframe and then replace the row values ​​with the corresponding column names.

Is there a good way to do this?

+3


source to share


1 answer


Use order

with apply

, fetching names

in process, for example:

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 apply

must be t

carried over before it is recombined with the Id column.

+5


source







All Articles