Change row order in a matrix/dataframe

There probably are more elegant ways, but this works:

m <- matrix(1:9, ncol=3, byrow=TRUE)

# m[rev(seq_len(nrow(m))), ]  # Initial answer
m[nrow(m):1, ]
     [,1] [,2] [,3]
[1,]    7    8    9
[2,]    4    5    6
[3,]    1    2    3

This works because you are indexing the matrix with a reversed sequence of integers as the row index. nrow(m):1 results in 3 2 1.


I would reverse the rows an index starting with the number of rows, along this line

revdata <-  thedata[dim(thedata)[1L]:1,]

You can reverse the order of a data.frame using the dplyr package:

iris %>% arrange(-row_number())

Or without using the pipe-operator by doing

arrange(iris, -row_number())