R语言如何返回矩阵按值排序后所有元素对应的行列索引
R语言实现矩阵元素降序排列后输出对应行列索引
核心实现代码
# 生成示例矩阵 set.seed(1000) mymat <- matrix(round(runif(12, min=1, max=15),2), nrow = 3, ncol = 4, byrow = TRUE) # 按元素降序获取对应行列索引 sorted_index <- arrayInd(order(mymat, decreasing = TRUE), .dim = dim(mymat)) # 输出无行号的索引结果 print(sorted_index, row.names = FALSE)
运行输出结果
[,1] [,2] 2 2 3 3 1 4 3 4 2 4 2 1 1 1 3 1 1 2 3 2 2 3 1 3
带元素值注释的输出实现
如果你需要每行索引后标注对应元素值,可使用以下代码:
sorted_val <- sort(mymat, decreasing = TRUE) for (i in seq_len(nrow(sorted_index))) { cat(sorted_index[i, 1], sorted_index[i, 2], paste0("# 对应元素值为", sorted_val[i], "\n")) }
输出效果:
2 2 # 对应元素值为12.85 3 3 # 对应元素值为12.62 1 4 # 对应元素值为11.17 3 4 # 对应元素值为11.05 2 4 # 对应元素值为10.81 2 1 # 对应元素值为10.16 1 1 # 对应元素值为9.39 3 1 # 对应元素值为8.56 1 2 # 对应元素值为7.32 3 2 # 对应元素值为5.21 2 3 # 对应元素值为3.23 1 3 # 对应元素值为2.92
逻辑说明
order(mymat, decreasing = TRUE)返回矩阵所有元素按降序排列后的向量位置索引(矩阵默认按列优先展平为向量)arrayInd()可将向量位置索引批量转换为对应矩阵的行列索引- 若矩阵存在重复值,可给
order()添加method参数控制排序规则,默认按元素在矩阵中出现的先后顺序排列
内容的提问来源于stack exchange,提问作者Mathica
相关产品推荐
相关产品推荐

