How to reverse the order of a dataframe in R

前端 未结 7 800
终归单人心
终归单人心 2021-01-03 18:37

I\'ve endlessly looked for this and somehow nothing has solved this simple problem.

I have a dataframe called Prices in which there are 4 columns, one of wh

7条回答
  •  执笔经年
    2021-01-03 18:43

    Just for completeness sake. There is actually no need to call seq here. You can just use the :-R-logic:

    ### Create some sample data
    n=252
    sampledata<-data.frame(a=sample(letters,n,replace=TRUE),b=rnorm(n,1,0.7),
                           c=rnorm(n,1,0.6),d=runif(n))
    
    ### Compare some different ways to reorder the dataframe
    myfun1<-function(df=sampledata){df<-df[seq(nrow(df),1),]}
    myfun2<-function(df=sampledata){df<-df[seq(dim(df)[1],1),]}
    myfun3<-function(df=sampledata){df<-df[dim(df)[1]:1,]}
    myfun4<-function(df=sampledata){df<-df[nrow(df):1,]}
    
    ### Microbenchmark the functions
    
    
    microbenchmark::microbenchmark(myfun1(),myfun2(),myfun3(),myfun4(),times=1000L)
        Unit: microseconds
             expr    min     lq      mean  median      uq      max neval
         myfun1() 63.994 67.686 117.61797 71.3780 87.3765 5818.494  1000
         myfun2() 63.173 67.686  99.29120 70.9680 87.7865 2299.258  1000
         myfun3() 56.610 60.302  92.18913 62.7635 76.9155 3241.522  1000
         myfun4() 56.610 60.302  99.52666 63.1740 77.5310 4440.582  1000
    

    The fastest way in my trial here was to use df<-df[dim(df)[1]:1,]. However using nrow instead of dim is only slightly slower. Making this a question of personal preference.

    Using seq here definitely slows the process down.

    UPDATE September 2018:

    From a speed view there is little reason to use dplyr here. For maybe 90% of users the basic R functionality should suffice. The other 10% need to use dplyr for querying a database or need code translation into another language.

    ## hmhensen's function
    dplyr_fun<-function(df=sampledata){df %>% arrange(rev(rownames(.)))}
    
    microbenchmark::microbenchmark(myfun3(),myfun4(),dplyr_fun(),times=1000L)
    Unit: microseconds
            expr    min      lq      mean  median      uq    max neval
        myfun3()   55.8   69.75  132.8178  103.85  139.95 8949.3  1000
        myfun4()   55.9   68.40  115.6418  100.05  135.00 2409.1  1000
     dplyr_fun() 1364.8 1541.15 2173.0717 1786.10 2757.80 8434.8  1000
    

提交回复
热议问题