Find the column number of the smallest item in a specific row

Using R

Say, for example, you have a matrix like 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 particular row. For example, I want to know which column number has the smallest element in row 1. Therefore, the output should be 2. Since the smallest element in row 1 is -7 and is in column 2. I assume that the answer is very simple, but I just don’t I can do it! I tried to do the following, but that just gives me an answer of 5.

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

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

thanks

+1
algorithm matrix r which
source share
1 answer

If there is only one minimum for each row, you can find it with

 apply(C, 1, which.min) 

or (from R: search for a column with a minimum value in each row if there is a binding ). See ?max.col more details.

 max.col(-C, "first") 

edit (thanks @flodel in the comments)

You can do this for single lines.

 which.min(C[1,]) 

Or if there are several matches

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

You get 5 , because -7 is the fifth element of the matrix, since it matches the column. Take a look at c(C)

+5
source share

All Articles