Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change row order in a matrix/dataframe

I need to change/invert rows in my data frame, not transposing the data but moving the bottom row to the top and so on. If the data frame was:

1 2 3  4 5 6 7 8 9 

I need to convert to

7 8 9 4 5 6 1 2 3 

I've read about sort() but I don't think it is what I need or I'm not able to find the way.

like image 636
pacomet Avatar asked Aug 22 '11 10:08

pacomet


People also ask

How do I change the order of a row in a Dataframe in R?

To change the row order in an R data frame, we can use single square brackets and provide the row order at first place.

How do you reverse the order of rows in a matrix?

By using apply() with the second parameter (the margin) equal to 2 we loop through all the columns of n , and for each column we apply the function rev() , which reverses the entries of a vector. This simply reverses the order of the rows in the matrix.

How do I reverse a row in a matrix in R?

Rotating or transposing R objects 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.


2 Answers

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.

like image 136
Andrie Avatar answered Oct 03 '22 01:10

Andrie


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()) 
like image 37
Holger Brandl Avatar answered Oct 03 '22 01:10

Holger Brandl