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.
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
.
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())
I would reverse the rows an index starting with the number of rows, along this line
revdata <- thedata[dim(thedata)[1L]:1,]
I think this is the simplest way:
MyMatrix = matrix(1:20, ncol = 2)
MyMatrix[ nrow(MyMatrix):1, ]
If you want to reverse the columns, just do
MyMatrix[ , ncol(MyMatrix):1 ]
We can reverse the order of row.names (for data.frame only):
# create data.frame
m <- matrix(1:9, ncol=3, byrow=TRUE)
df_m <- data.frame(m)
#reverse
df_m[rev(rownames(df_m)), ]
# X1 X2 X3
# 3 7 8 9
# 2 4 5 6
# 1 1 2 3