sn-one
sn-one

Reputation: 45

Matrix not filling up with 1 where necessary in R

I am trying to fill a matrix with ones (1) where the index corresponds to the max of another matrix of the same dimension. below is a reproducible example

set.seed(1)
matric <- matrix(rnorm(3000), nrow = 500, ncol = 6)

best <- matrix(0, nrow = 500, ncol = 6)
n_end <- 500

for (i in n_end) {
  best[which(matric[i,] == max(matric[i,]))] <- 1
}
## the best model has the higher sum
best1 <- colSums(best)

Please Help!! :)

Upvotes: 2

Views: 39

Answers (1)

akrun
akrun

Reputation: 887221

We can use seq_len or 1:n_end and inside the loop, as we are assigning to the same row of 'best', index that matrix as well

for(i in 1:n_end) {
  best[i,][matric[i,] == max(matric[i,])] <- 1
 }

Or if there is only a single max value per row, then use max.col as it is faster and vectorized

best[cbind(seq_len(nrow(best)), max.col(matric, 'first'))] <- 1

Or with rowMaxs from matrixStats

library(matrixStats)
+(matric == rowMaxs(matric))

Upvotes: 2

Related Questions