矩阵每一列的最小行的返回索引 [英] Return Index of Minimum Row for Each Column of Matrix

查看:101
本文介绍了矩阵每一列的最小行的返回索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类似下面示例的矩阵,称为m1:

Suppose I have a matrix like the example below called m1:

m1<-matrix(6:1,nrow=3,ncol=2)
     [,1] [,2]
[1,]    6    3
[2,]    5    2
[3,]    4    1

如何获取每一列最小值的索引行? 我知道which.min()将返回每一行的列索引值.

How do I get the index row for the minimum value of each column? I know which.min() will return the column index value for each row.

输出应为:3和3,因为列[,1]的最小值是4对应于行[3,],列[,2]的最小值是1对应于行[3,].

The output should be: 3 and 3 because the minimum for column [,1] is 4 corresponding to row [3,] and the minimum for column [,2] is 1 corresponding row [3,].

推荐答案

如果我们需要按列索引,请使用applyMARGIN=2并应用which.min

If we need column wise index use apply with MARGIN=2 and apply the which.min

apply(m1, 2, which.min)
#[1] 3 3

如果一次需要一列:

apply(as.matrix(m1[,1, drop = FALSE]), 2, which.min)

如果选中?Extract,则默认用法为

If we check ?Extract, the default usage is

x [i,j,...,drop = TRUE]

x[i, j, ... , drop = TRUE]

drop-用于矩阵和数组.如果为TRUE,则结果强制为最小尺寸(请参见示例).这仅适用于提取元素,不适用于替换.有关更多详细信息,请参见drop.

drop - For matrices and arrays. If TRUE the result is coerced to the lowest possible dimension (see the examples). This only works for extracting elements, not for the replacement. See drop for further details.

为避免尺寸下降,请使用drop = FALSE

To avoid getting dimensions dropped, use drop = FALSE

如果我们需要每一行的最小值

If we need the min values of each row

do.call(pmin, as.data.frame(m1))

apply(m1, 2, min)

library(matrixStats)
rowMins(m1)

数据

m1 <- matrix(6:1,nrow=3,ncol=2)

这篇关于矩阵每一列的最小行的返回索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆