r - 定位输出矩阵的哪些元素
问题描述
如果我有一个 100 x 100 矩阵并且我想找到最高的 20 个值并且我成功地使用:
mat <- matrix(data = rexp(200, rate = 10), nrow = 100, ncol = 100)
tail(sort(mat), 20)
#[1] 0.6599044 0.6599044 0.6599044 0.6599044 0.6599044 0.6601134 0.6601134 0.6601134 0.6601134 0.6601134
#[11] 0.6669251 0.6669251 0.6669251 0.6669251 0.6669251 1.0284198 1.0284198 1.0284198 1.0284198 1.0284198
但是现在我如何在矩阵中输出它们的位置?
解决方案
我们可以使用order
和arrayInd
运行。
mat <- matrix(data = rexp(200, rate = 10), nrow = 100, ncol = 100)
arrayInd(order(mat, decreasing = TRUE)[1:20], .dim = dim(mat))
一个小例子
set.seed(0)
mat <- round(matrix(data = rexp(25, rate = 10), nrow = 5, ncol = 5), 4)
# [,1] [,2] [,3] [,4] [,5]
#[1,] 0.0184 0.1230 0.0762 0.1876 0.0642
#[2,] 0.0146 0.0540 0.1238 0.0655 0.0294
#[3,] 0.0140 0.0957 0.4424 0.0337 0.0566
#[4,] 0.0436 0.0147 0.1055 0.0588 0.0106
#[5,] 0.2895 0.1391 0.1035 0.2365 0.0059
## 1D index of the first 4 largest values
ind1D <- order(mat, decreasing = TRUE)[1:4]
# [1] 13 5 20 16
## 2D index
ind2D <- arrayInd(ind1D, .dim = dim(mat))
# [,1] [,2]
#[1,] 3 3
#[2,] 5 1
#[3,] 5 4
#[4,] 1 4
## inspect corresponding matrix elements, using either 1D or 2D index
mat[ind1D]
#[1] 0.4424 0.2895 0.2365 0.1876
mat[ind2D]
#[1] 0.4424 0.2895 0.2365 0.1876
还有一个.dimanmes
参数arrayInd
可以设置。arrayInd
是 的主力军which(, arr.ind = TRUE)
。
推荐阅读
- c# - 如何在不更改 app.config(.NET 框架)的情况下让 VSTest 使用 ServerGC?
- javascript - 如何以日期格式显示时间?
- c# - 向 InkCanvas 添加笔画并从 WPF 中的克隆中删除?
- javascript - 这是在前端硬编码权限的好方法吗?
- sequelize.js - 别名外键不适用于续集 5.21.9
- c++ - 加入作为类成员的线程的正确方法?
- sql - 春季 JPA 查询。使用 @OneToMany 属性连接表
- scala - scala.collection.Map[Int, T] 的函子
- python - 了解 torch.nn.Flatten
- c# - 错误 CS0103:当前上下文中不存在该名称;系统无法识别我的列表