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

标签 r matrix apply

你知道一个 R 函数可以在不使用 apply 的情况下对矩阵的每一列进行排序吗:

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 函数,它可以在不使用像这样的 apply 的情况下返回矩阵每列的 max 向量?

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

谢谢。

最佳答案

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

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])
}

关于r - 如何用R函数对矩阵的每一列进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70951810/

相关文章:

r - Gamma GLM : NaN production and divergence errors

python - 如何为 numpy 矩阵生成干净的 x 和 y 轴?

python - 在下一次应用迭代 python 中使用应用 fnc 的输出

python - Pandas,将自定义函数应用于按字符串索引分组的数据

python - 四舍五入到小数点

r - 如何将 [i] 的每个元素的 j=1 相加到 (i-1)(文章中的输入公式)

r - 如何更改 R 中随机森林的分割标准?

javascript - SSRS : Action "Go to URL" not working after applied to data cell in matrix

java - `Matrix.setRotate` 和 `Matrix.postRotate` 有什么区别

Python 与 R : apply a function to each element in a vector