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!
We use DataFrame. reindex() function to reorder the rows using the index list.
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.
To change the row order in an R data frame, we can use single square brackets and provide the row order at first place.
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,]
You could also try
df[nrow(df):1,]
This arranges the rows in reverse order for any dataframe df
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With