Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reorder columns based on values in a particular row.

I have the following data in a dataframe:

  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 transformation would be:

  bb  cc  aa
1 4  5  3
2 4  3  5 
3 8  6  7
...
100 63 55 33
like image 524
learner Avatar asked Aug 27 '12 18:08

learner


People also ask

How do I sort column orders in R?

To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.

How do you sort a Dataframe according to a column in R?

Methods to sort a dataframe:order() function (increasing and decreasing order) arrange() function from dplyr package. setorder() function from data. table package.


1 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),])]
like image 54
Joshua Ulrich Avatar answered Sep 25 '22 12:09

Joshua Ulrich