Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Change row order

Tags:

r

Assume a dataframe constructed like

df = data.frame(replicate(2,sample(0:10,2,rep=TRUE)))
df = t(df)
df

which returns something like

   [,1] [,2]
X1    9    8
X2   10    4

Here's the question: How can I change the order of rows so that:

   [,1] [,2]
X2   10    4
X1    9    8

? Thanks!

like image 712
Christopher Avatar asked Sep 15 '15 18:09

Christopher


People also ask

How do I change the order of rows in a data frame?

We use DataFrame. reindex() function to reorder the rows using the index list.

How do I reverse the order of rows in R?

The rev() method in R is used to return the reversed order of the R object, be it dataframe or a vector. It computes the reverse columns by default. The resultant dataframe returns the last column first followed by the previous columns. The ordering of the rows remains unmodified.

How do I change the row position 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.


Video Answer


3 Answers

One way to do it is to index the row directly:

df[c("X2","X1"),]

Or you could use the row indices:

df[c(2,1),]  # or just df[2:1,]
like image 177
nimrodm Avatar answered Oct 21 '22 05:10

nimrodm


You could also try

df[nrow(df):1,]

This arranges the rows in reverse order for any dataframe df.

like image 43
RHertel Avatar answered Oct 21 '22 03:10

RHertel


Suppose you want to switch the 8 and 9 rows. The data frame has n rows in total.

mydata[c(1:7,9,8,10:nrow(mydata)), ] # new order 
like image 26
Steinhafen Avatar answered Oct 21 '22 05:10

Steinhafen