更改矩阵/数据框中的行顺序 [英] 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屋!
查看全文