更改矩阵/数据帧中的行顺序 [英] 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
我需要转换为
7 8 9
4 5 6
1 2 3
我已经阅读了 sort()
,但我不认为这是我需要的,或者我无法找到方法。
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
这是因为您使用反向的整数序列作为行索引来索引矩阵。 nrow(m):1
结果 3 2 1
。
这篇关于更改矩阵/数据帧中的行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文