如何用R函数对矩阵的每一列进行排序?

How to sort each column of matrix with R function?

您是否知道一个 R 函数可以对矩阵的每一列进行排序而不使用像这样的应用:

mat= matrix(c(1,2,0,-7,-4,7,8,3,12,15,23,-21),nrow = 4,ncol = 3)
apply(mat,2,sort)
##
     [,1] [,2] [,3]
[1,]   -7   -4  -21
[2,]    0    3   12
[3,]    1    7   15
[4,]    2    8   23

你是否也知道一个 R 函数,它 return 一个矩阵的每一列的最大值的向量而不使用像这样应用?

mat2=matrix(c(2,1,0,-7,-4,7,8,3,12,15,23,-21),nrow = 3,ncol = 4)
apply(mat2,2,max)
##
[1]  2  7 12 23

谢谢。

排序的一种可能性是使用 colSort from Rfast:

Rfast::colSort(mat)

     [,1] [,2] [,3]
[1,]   -7   -4  -21
[2,]    0    3   12
[3,]    1    7   15
[4,]    2    8   23

我们还可以使用 Rfast 获取每列的最大值:

Rfast::colMaxs(mat2, value = TRUE)

[1]  2  7 12 23

另一种排序方式是使用简单的 for 循环:

for(i in 1:ncol(mat)){
  mat[,i] <- sort(mat[,i])
}

也可以使用简单的 for 循环来获取最大值:

max <- 0
for(i in 1:ncol(mat2)){
  max[i] <- max(mat2[,i])
}

如果您真的想避免使用 *apply 系列,您可以尝试以下几种选择

  • order方法
> `dim<-`(mat[order(col(mat), mat)], dim(mat))
     [,1] [,2] [,3]
[1,]   -7   -4  -21
[2,]    0    3   12
[3,]    1    7   15
[4,]    2    8   23

> `dim<-`(mat2[order(col(mat2), -mat2)], dim(mat2))[1, ]
[1]  2  7 12 23
  • ave方法
> ave(mat, col(mat), FUN = sort)
     [,1] [,2] [,3]
[1,]   -7   -4  -21
[2,]    0    3   12
[3,]    1    7   15
[4,]    2    8   23


> unique(ave(mat2, col(mat2), FUN = max))
     [,1] [,2] [,3] [,4]
[1,]    2    7   12   23

> ave(mat2, col(mat2), FUN = max)[1, ]
[1]  2  7 12 23
  • aggregate方法
> `dim<-`(unlist(aggregate(mat, list(rep(1, nrow(mat))), sort)[-1]), dim(mat))
     [,1] [,2] [,3]
[1,]   -7   -4  -21
[2,]    0    3   12
[3,]    1    7   15
[4,]    2    8   23

> unlist(aggregate(mat2, list(rep(1, nrow(mat2))), max)[-1])
V1 V2 V3 V4
 2  7 12 23