-1

I want sort a data frame by datas of a column (the first column, called Initial). My data frame it's: I called my dataframe: t2

Initial            Final        Changes
    1              1              200
    1              3              500
    3              1              250
    24             25             175
    21             25             180
    1              5             265
    3              3             147

I am trying with code:

t2 <- t2[order(t2$Initial, t2$Final, decreasing=False),]

But, the result is of the type:

Initial            Final       Changes
     3              1              250
     3              3             147
    21             25             180
    24             25             175
    1              5              265
    1              1              200
    1              3              500

And when I try with code:

t2 <- t2[order(t2$Initial, t2$Final, decreasing=TRUE),]

The result is:

Initial            Final       Changes
    1              5           265
    1              1           200
    1              3           500    
    24             25          175
    21             25          180
    3              1           250
    3              3           147

I don't understand what happen. Can you help me, please?

  • What is your expected output ? Do you need `t2[order(t2$Initial), ]` Or `t2[with(t2, order(Initial, -Final)), ]` ? – Ronak Shah Dec 05 '19 at 03:22
  • This is a good example of why it's important to provide [reproducible data](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). I suspect akrun's answer correctly identifies the problem, but it's impossible to tell the underlying storage of `t2` from looking at text. – thelatemail Dec 05 '19 at 03:32

1 Answers1

3

It is possible that the column types are factors, in that case, convert it to numeric and should work

library(dplyr)
t2 %>%        
    arrange_at(1:2, ~ desc(as.numeric(as.character(.))))

Or with base R

t2[1:2] <- lapply(t2[1:2], function(x) as.numeric(as.character(x)))
t2[do.call(order, c(t2[1:2], decreasing = TRUE)), ]

Or the OP's code should work as well


Noticed that decreasing = False in the first option OP tried (may be a typo). In R, it is upper case, FALSE

t2[order(t2$Initial, t2$Final, decreasing=FALSE),]
akrun
  • 874,273
  • 37
  • 540
  • 662