Reversing order column data.frame

4

I have this date frame:

> head(df1)
         data    spread
1 2006-01-01   -3.0404577
2 2006-02-01   -3.3902628
3 2006-03-01   -2.5283960
4 2006-04-01   -1.5279234
5 2006-05-01   -0.0897918
6 2006-06-01    1.0286549
> tail(df1)
         data    spread
112 2015-04-01   -0.2923391
113 2015-05-01   -0.8202538
114 2015-06-01   -1.0975489
115 2015-07-01   -1.1600462
116 2015-08-01   -0.4637534
117 2015-09-01    1.2141885

I want to invert the column and data order:

I made this command:

df1<-df1[order(rev(df1$data),rev(df1$spread)),]

It shuffles and leaves it disorganized:

> head(df1)
      data          spread
114 jun2015 -1.09754890
110 fev2015  0.06755755
106 out2014  0.87560496
116 ago2015 -0.46375344
117 set2015  1.21418847
111 mar2015  0.32772727
> tail(MatrizVerticeSpreadMensala)
      data          spread
9 set2006  0.0742353
3 mar2006 -2.5283960
4 abr2006 -1.5279234
5 mai2006 -0.0897918
7 jul2006  0.5451561
1 jan2006 -3.0404577

Any suggestions?

Thank you!

    
asked by anonymous 14.10.2015 / 22:59

2 answers

2

Recreating your database

df<- read.table(text="data    spread
1 2006-01-01   -3.0404577
2 2006-02-01   -3.3902628
3 2006-03-01   -2.5283960
4 2006-04-01   -1.5279234
5 2006-05-01   -0.0897918
6 2006-06-01    1.0286549
112 2015-04-01   -0.2923391
113 2015-05-01   -0.8202538
114 2015-06-01   -1.0975489
115 2015-07-01   -1.1600462
116 2015-08-01   -0.4637534
117 2015-09-01    1.2141885")

Using the command rev() to do what you want (reverse the order of columns and data).

rev(df[nrow(df):1,])

        spread       data
117  1.2141885 2015-09-01
116 -0.4637534 2015-08-01
115 -1.1600462 2015-07-01
114 -1.0975489 2015-06-01
113 -0.8202538 2015-05-01
112 -0.2923391 2015-04-01
6    1.0286549 2006-06-01
5   -0.0897918 2006-05-01
4   -1.5279234 2006-04-01
3   -2.5283960 2006-03-01
2   -3.3902628 2006-02-01
1   -3.0404577 2006-01-01
    
14.10.2015 / 23:12
1

Hypothetically, I re-created your data using the lubridate and dylyr packages.

library (lubridate)
dados<-data.frame(data=seq(ymd('2006/01/01'),ymd('2015/09/01'),by='1 month'),spread=rnorm(117))

To reverse, in this case simply by rearranging the dates, I applied the following expression:

library (dplyr)                  
dados_ordenados<-dados %>% arrange(desc(data))

Where:

  • % >% is a pipe operator that simplifies the expression f (x) ;
  • arrange is a sort function and;
  • desc organizes in descending order.

And to reposition your columns:

posicao_dados<- dados_ordenados  %>%  select(spread, everything())  

Where:

  • everything () is everything else.
01.11.2015 / 18:33