isemaj
isemaj

Reputation: 587

Reorder the rows of data frame in dplyr

How can I reorder the data frame? Where I would like the bottom row to be on the top and the top will be on the bottom (reverse).

Upvotes: 1

Views: 407

Answers (2)

akrun
akrun

Reputation: 886968

An easier option is to just do nrow(df):1 as the row index

df[nrow(df):1, ]

Or in data.table

library(data.table)
setDT(df)[.N:1]

Or an option with dplyr

library(dplyr)
df %>% 
  arrange(desc(row_number()))

Upvotes: 3

Ronak Shah
Ronak Shah

Reputation: 388817

If you just want to reverse the dataframe, there are multiple ways to do this.

One way in base R would be using rev

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

#    a  b
#10 10 20
#9   9 19
#8   8 18
#7   7 17
#6   6 16
#5   5 15
#4   4 14
#3   3 13
#2   2 12
#1   1 11

If interested in dplyr solution we could do

library(dplyr)
df %>% slice(n() - row_number() + 1)

data

 df <- data.frame(a = 1:10, b = 11:20)

Upvotes: 4

Related Questions