Modify matrix to keep nth largest values of every row

Hello all,

I am working with a large matrix, but I am only interested in keeping the nth largest values of every row, making the rest of values equal to 0.

I will use a simple example:

n = 5 # Number of dimensions

A = matrix(runif(n^2), n) # Random matrix example

How could I keep the largest k=2 values of every row, while making the rest of values equal to 0 ?

Thanks in advance for any help!

n = 5 # Number of dimensions

A = matrix(runif(n^2), n) # Random matrix example

do_a_row <- function(row,k=2){
  keepers <- tail(sort(row),n=k)
  row[which(! row %in% keepers)] <- 0
  row
}

A
(B <- t(apply(A,MARGIN = 1,do_a_row)))
2 Likes

Thanks @nirgrahamuk ! That was exactly what I was looking for

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.