Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order a data frame by one descending and one ascending column?

I have a data frame, which looks like that:

    P1  P2  P3  T1  T2  T3  I1  I2 1   2   3   5   52  43  61  6   "b" 2   6   4   3   72  NA  59  1   "a" 3   1   5   6   55  48  60  6   "f" 4   2   4   4   65  64  58  2   "b" 

I want to sort it by I1 in descending order, and rows with the same value in I1 by I2 in ascending order, getting the rows in the order 1 3 4 2. But the order function seems to only take one decreasing argument, which is then TRUE or FALSE for all ordering vectors at once. How do I get my sort correct?

like image 359
rumtscho Avatar asked Oct 17 '11 11:10

rumtscho


People also ask

How do you order a data frame from a specific column?

Sorting Your DataFrame on a Single Column. To sort the DataFrame based on the values in a single column, you'll use . sort_values() . By default, this will return a new DataFrame sorted in ascending order.

How do you sort a DataFrame by a column in descending order?

We can sort it by using the dataframe. sort_index() function. Alternatively, you can sort the index in descending order by passing in the ascending=False the argument in the function above.

How do you sort a DataFrame in R by one of the columns?

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.


2 Answers

I used this code to produce your desired output. Is this what you were after?

rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2 2   3   5   52  43  61  6   b 6   4   3   72  NA  59  1   a 1   5   6   55  48  60  6   f 2   4   4   65  64  58  2   b"), header = TRUE) rum$I2 <- as.character(rum$I2) rum[order(rum$I1, rev(rum$I2), decreasing = TRUE), ]    P1 P2 P3 T1 T2 T3 I1 I2 1  2  3  5 52 43 61  6  b 3  1  5  6 55 48 60  6  f 4  2  4  4 65 64 58  2  b 2  6  4  3 72 NA 59  1  a 
like image 188
Roman Luštrik Avatar answered Oct 17 '22 08:10

Roman Luštrik


I use rank:

rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2 2   3   5   52  43  61  6   b 6   4   3   72  NA  59  1   a 1   5   6   55  48  60  6   f 2   4   4   65  64  58  2   b 1   5   6   55  48  60  6   c"), header = TRUE)  > rum[order(rum$I1, -rank(rum$I2), decreasing = TRUE), ]   P1 P2 P3 T1 T2 T3 I1 I2 1  2  3  5 52 43 61  6  b 5  1  5  6 55 48 60  6  c 3  1  5  6 55 48 60  6  f 4  2  4  4 65 64 58  2  b 2  6  4  3 72 NA 59  1  a 
like image 39
Michele Avatar answered Oct 17 '22 07:10

Michele