只需使用:
A[order(A[,k]),]
Run Code Online (Sandbox Code Playgroud)
例如:
set.seed(21)
A <- matrix(rnorm(50),10,5)
A[order(A[,1]),]
Run Code Online (Sandbox Code Playgroud)
详细说明@joshua的答案:我认为混淆可能是因为你在列上排序然后将该排序作为索引传递给行.
这可能就是为什么你尝试A[, order(A[,k])] 而不是 A[order(A[,k]),]
order(x)与名称相反,实际上并不是命令 x,而
只是提供了一个排序 x.
例如:
set.seed(1)
A <- matrix(sample(LETTERS[2:8], 24, T), ncol=6)
print(A, quote=F)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] C C F F G H
[2,] D H B D H C
[3,] F H C G D F
[4,] H F C E G B
order(A[, 2])
[1] 1 4 2 3
Run Code Online (Sandbox Code Playgroud)
*请注意,输出只有4个元素长,这是A 的行数,而不是列数.*
输出基本上表示在A的第2列中,
但是A列的每个元素都附加到一行.我们需要重新排序行而不是列.
要将该排序应用于整个矩阵(或数据框),我们将排序用作行索引:
rowIndex <- order(A[, 2])
# Note that these are all equivalent
A[rowIndex, ]
A[order(A[, 2]), ]
A[c(1, 4, 1, 3), ]
Run Code Online (Sandbox Code Playgroud)
最后,我们可以传递order()多个向量,它将使用后续向量来破坏关系.但是,无论我们给出的A的列数是多少,order仍然会给我们一个向量,大小与A的行数相等:
# Order according to column 2; ties are left according to their original order
order(A[, 2])
[1] 1 4 2 3
# Order according to column 2; ties are ordered according to column 5
order(A[, 2], A[, 5])
[1] 1 4 3 2
Run Code Online (Sandbox Code Playgroud)