Christopher
Christopher

Reputation: 2232

R: Change row order

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!

Upvotes: 9

Views: 49042

Answers (4)

Steinhafen
Steinhafen

Reputation: 71

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 

Upvotes: 3

Nirmit Shah
Nirmit Shah

Reputation: 1

You can use the following:

Subset(nameofthedataframe,Select = c(Namelist))

Upvotes: 0

RHertel
RHertel

Reputation: 23788

You could also try

df[nrow(df):1,]

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

Upvotes: 3

nimrodm
nimrodm

Reputation: 23799

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,]

Upvotes: 19

Related Questions