对R中的矩阵列进行排序
我有一个矩阵x,其中有以下形式的几列和几行:对R中的矩阵列进行排序,r,sorting,R,Sorting,我有一个矩阵x,其中有以下形式的几列和几行: 2 5 3 6 4 3 6 4 2 5 4 2 5 3 6 我希望列升序为applyx,2,sor,然后列升序为列中的平均值 输出如下所示: 2 2 3 2 3 3 3 4 5 5 4 6 5 6 6 资料 您可以执行以下操作: 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[,
2 5 3 6 4
3 6 4 2 5
4 2 5 3 6
我希望列升序为applyx,2,sor,然后列升序为列中的平均值
输出如下所示:
2 2 3 2 3
3 3 4 5 5
4 6 5 6 6
资料
您可以执行以下操作:
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
这是你的矩阵
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
你能详细解释一下你所说的“以后按列中的平均值对列进行升序”是什么意思吗?我想,这可能是重复的,但不是重复的。我必须计算每一列的平均值,下一列按升序排序。您的预期输出仍然没有意义。哦,非常抱歉,但firsr矩阵不正确,我更正了它,谢谢您的回答
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