Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
785 views
in Technique[技术] by (71.8m points)

r - Finding the column number of the smallest element in a certain row

Using 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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

apply(C, 1, which.min)

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")

edit (thanks to @flodel in the comments)

You can do this for individual rows by

which.min(C[1,])

Or if there are multiple matches

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...