Reorder columns based on values ​​in a specific row.

I have the following data in a data frame:

  aa bb  cc
1 3 4 5
2 5 4 3
3 7 8 6 
..
100 33 63 55

I need to reorder the columns based on the values ​​in the last row. The result of this conversion will be:

  bb  cc  aa
1 4  5  3
2 4  3  5 
3 8  6  7
...
100 63 55 33
+6
source share
2 answers
x <- structure(list(aa = c(3L, 5L, 7L, 33L), bb = c(4L, 4L, 8L, 63L),
  cc = c(5L, 3L, 6L, 55L)), .Names = c("aa", "bb", "cc"),
  class = "data.frame", row.names = c("1", "2", "3", "100"))
x[,order(-x[nrow(x),])]
+7
source

Based on Joshua Ulrich's answer, answer if you want to sort by name , not by number:

x[, order(-x[which(rownames(x) == '100'), ]) ]

where 100is the name of the string, as in the above example.

+1
source

All Articles