Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse the order of a dataframe in R

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 which is a list of historical dates - the other 3 are lists of prices for products.

1   10/10/2016  53.14   50.366  51.87 2   07/10/2016  51.93   49.207  50.38 3   06/10/2016  52.51   49.655  50.98 4   05/10/2016  51.86   49.076  50.38 5   04/10/2016  50.87   48.186  49.3 6   03/10/2016  50.89   48.075  49.4 7   30/09/2016  50.19   47.384  48.82 8   29/09/2016  49.81   46.924  48.4 9   28/09/2016  49.24   46.062  47.65 10  27/09/2016  46.52   43.599  45.24 

The list is 252 prices long. How can I have my output stored with the latest date at the bottom of the list and the corresponding prices listed with the latest prices at the bottom of the list?

like image 846
jmn8 Avatar asked Oct 11 '16 10:10

jmn8


People also ask

How do I reverse a Dataframe in R?

You can rotate the data. frame so that the rows become the columns and the columns become the rows. That is, you transpose the rows and columns. You simply use the t() command.

How do I reverse the order of a list in R?

To reverse a list in R programming, call rev() function and pass given list as argument to it. rev() function returns returns a new list with the contents of given list in reversed order.

What does rev () do in R?

rev() function in R Language is used to return the reverse version of data objects. The data objects can be defined as Vectors, Data Frames by Columns & by Rows, etc.


2 Answers

Another tidyverse solution and I think the simplest one is:

df %>% map_df(rev)

or using just purrr::map_df we can do map_df(df, rev).

like image 151
pasipasi Avatar answered Sep 29 '22 10:09

pasipasi


If you just want to reverse the order of the rows in a dataframe, you can do the following:

df<- df[seq(dim(df)[1],1),] 
like image 24
user7559006 Avatar answered Sep 29 '22 10:09

user7559006