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

前端 未结 1 1975
别那么骄傲
别那么骄傲 2020-12-21 19:30

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条回答
  • 2020-12-21 20:17

    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)

    0 讨论(0)
提交回复
热议问题