我有一个矩阵(x),其中包含以下几种形式的行和列:
2 5 3 6 4
3 6 4 2 5
4 2 5 3 6
我希望排序列升序apply(x,2,sort)
,然后按列升级列中的列。
输出如下:
2 2 3 2 3
3 3 4 5 5
4 6 5 6 6
数据
x <- structure(c(2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 6, 6), .Dim = c(3L, 5L))
答案 0 :(得分:1)
您可以执行以下操作:
A <- matrix(c(2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 6, 6), ncol=5)
B <- apply(A, 2, sort)
C <- B[, order(apply(B, 2, sum), decreasing = FALSE)]
> C
[,1] [,2] [,3] [,4] [,5]
[1,] 2 2 3 2 4
[2,] 3 3 4 5 6
[3,] 4 6 5 6 6
答案 1 :(得分:1)
这是你的矩阵
mat <- matrix(c(2,5, 3, 6, 4,3 ,6 ,4 ,2 ,6, 4 ,2 ,5, 3, 6), byrow=T, nrow=3, ncol = 5)
mat
[,1] [,2] [,3] [,4] [,5]
[1,] 2 5 3 6 4
[2,] 3 6 4 2 6
[3,] 4 2 5 3 6
以升序方式对列进行排序
mat_colsort <- apply(mat,2,sort)
mat_colsort
[,1] [,2] [,3] [,4] [,5]
[1,] 2 2 3 2 4
[2,] 3 5 4 3 6
[3,] 4 6 5 6 6
获取列意味着
avgs <- colMeans(mat_colsort)
查找列均值的递增顺序
neworder <- order(avgs)
适当地重新排序矩阵
sorted_matrix <- mat_colsort[,neworder]
sorted_matrix
[,1] [,2] [,3] [,4] [,5]
[1,] 2 2 3 2 4
[2,] 3 3 4 5 6
[3,] 4 6 5 6 6