发现在某一行中的最小元件的列数 [英] Finding the column number of the smallest element in a certain row

查看:170
本文介绍了发现在某一行中的最小元件的列数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于R

例如说,你有一个矩阵,如下面的人。

Say for example you have a matrix such as the one below.

    > C<-matrix(c(0,-7,2,8,0,0,3,7,0,3,0,3,0,0,0,0),nrow=4,byrow=TRUE)
> C
     [,1] [,2] [,3] [,4]
[1,]    0   -7    2    8
[2,]    0    0    3    7
[3,]    0    3    0    3
[4,]    0    0    0    0

你如何找到在某一行中的最小元件的列数。例如,我想知道列数第1行中最小的元素。因此输出应该只是2作为最小的元素在第1行是-7,并且在第2列。我假设的答案是很容易的,但我似乎无法做到这一点!我试图做以下,但它只是给了我5个问题的答案。

How do you find the column number of the smallest element in a certain row. For example I want to know what column number the smallest element in row 1 is. Therefore the output should just be 2. As the smallest element in row 1 is -7 and that is in column 2. I'm assuming the answer is very easy but i just can't seem to do it! I tried doing the following but it just gives me the answer of 5.

> inds = which(C == min(C[1,]))
> inds
[1] 5

可有人还告诉我是什么5手段,这种特殊情况下?

Can someone also tell me what the 5 means in this particular case?

感谢

推荐答案

如果只有一个最低限度的每一行,你可以找到它

If there is only a single minimum for each row you can find it with

apply(C, 1, which.min)

或(从<一个href="http://stackoverflow.com/questions/5495289/r-finding-column-with-minimum-value-in-each-row-when-there-is-a-tied">R:发现与最小值列中各行的时候有一个绑)。请参阅?max.col 更多选项。

or (from R: finding column with minimum value in each row when there is a tied). See ?max.col for more options.

max.col(-C, "first")

修改(感谢在评论@flodel)

edit (thanks to @flodel in the comments)

您可以通过

which.min(C[1,])

或者,如果有多个匹配

Or if there are multiple matches

apply(C, 1, function(i) which(i == min(i)))

您获得 5 ,因为 -7 是矩阵的第五元素,因为它的推移列明智的。看看 C(C)

You get 5, as -7 is the fifth element of the matrix as it goes column wise. Look at c(C)

这篇关于发现在某一行中的最小元件的列数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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