简体   繁体   中英

Keep one maximum value per row in a matrix in R

I have a matrix like this:

     [,1] [,2] [,3]
[1,]    0    1    0
[2,]    1    1    0
[3,]    0    0    1

The ones in each row represent the maximum values per row for eg i had the matrix

     [,1] [,2] [,3]
[1,]   11   32   12
[2,]   16   16   14
[3,]   19   18   27

Now in this matrix in the second row I had two same maximum values (16) which got replaced by two 1's in the second row in the previous matrix, now I want to remove duplicate maximum values in my rows of a matrix so in essence what I need is something like this:

     [,1] [,2] [,3]
[1,]    0    1    0
[2,]    1    0    0
[3,]    0    0    1

ie keep one maximum value per row at random (ties should be broken at random and only one maximum value kept) and make all the entries other than that zero. Please can any one provide me a code snippet to solve this problem.

if mat is your original matrix,

Create an empty matrix full of zeros, of the correct size and dim

ret <- matrix(rep(0, length(mat)), ncol=ncol(mat))

assign the required values to 1. Note that which.max breaks tie by choosing the first occurrence.

ret[ cbind(seq(nrow(mat)), apply(mat, 1, which.max))  ] <- 1

ret
     [,1] [,2] [,3]
[1,]    0    1    0
[2,]    1    0    0
[3,]    0    0    1

Alternatively, if you truly want to split ties at random, you would use something like this as the index to ret :

cbind(seq(nrow(mat)), apply(mat, 1, function(x) 
     sample(which(x == max(x)), 1)
))

Or you could use. This would be faster.

  ret[cbind(seq_len(nrow(mat2)),max.col(mat2, "first"))] <- 1
  ret
  #     [,1] [,2] [,3]
  #[1,]    0    1    0
  #[2,]    1    0    0
  #[3,]    0    0    1

data

 mat1 <- matrix(c(0,1,0, 1,1,0,0,0,1), ncol=3)
 mat2 <- matrix(c(11,16,19, 32, 16, 18, 12, 14, 27), ncol=3)
 ret <- matrix(0, ncol(mat1), nrow(mat1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM