-2

How can I invert the rows of a dataframe/tibble using dplyr? I don't want to arrange it by a certain variable, but rather have it just inverted.

I.e. the tibble

# A tibble: 5 x 2
      a b    
  <int> <chr>
1     1 one  
2     2 two  
3     3 three
4     4 four 
5     5 five 

should become

# A tibble: 5 x 2
      a b    
  <int> <chr>
1     5 five 
2     4 four 
3     3 three
4     2 two  
5     1 one  
Salim B
  • 2,409
  • 21
  • 32
  • @jaap You marked this question as a duplicate of [this question](https://stackoverflow.com/questions/47144143/dplyr-arrange-by-reverse-alphabetical-order) which is simply **not true**. Arranging a dataframe by a certain variable is not (necessarily) the same as inverting its rows. I've updated my question (already some time ago) to stress that. Could you please remove the duplicate marking? – Salim B Sep 10 '19 at 12:55
  • For your conveniance I've added another target which gives an even better illustration on reverting the order of a dataframe. Consequently I'm not going to remove the duplicate mark. – Jaap Sep 10 '19 at 15:16
  • 1
    Ok, the second linked question makes more sense since it actually gives the answer I'm asking for (`arrange(desc(row_number()))`). – Salim B Sep 10 '19 at 17:07

2 Answers2

6

Just arrange() by descending row_number() like this:

my_tibble %>%
  dplyr::arrange(-dplyr::row_number())
Salim B
  • 2,409
  • 21
  • 32
1

We can use desc

my_tibble %>% 
    arrange(desc(row_number()))

Or another option is slice

my_tibble %>%
    slice(rev(row_number()))

Or the 'a' column

my_tibble %>% 
   arrange(desc(a))
#  a     b
#1 5  five
#2 4  four
#3 3 three
#4 2   two
#5 1   one
akrun
  • 874,273
  • 37
  • 540
  • 662