Thelonious Monk
Thelonious Monk

Reputation: 466

Get the most occurring digit in a row of a matrix and concatenate results

I have a matrix eval_matrix which has dimensions (200,45). I want to get the most occurring digit in each row and want to make a new matrix maj of 200 rows and one column.

I am trying this:

maj=c()
for (i in nrow(eval_matrix)){
  m=names(which.max(table(eval_matrix[i,])))
  m<-as.numeric(m)
  maj<-rbind(maj,m)
}
View(maj)

But it is only giving me the last row's result in my new matrix maj.

What's going wrong here?

Upvotes: 0

Views: 28

Answers (1)

Karolis Koncevičius
Karolis Koncevičius

Reputation: 9656

You can also use apply() over each row of a matrix and turn the result into a one-column matrix. In a single line:

matrix(as.numeric(apply(eval_matrix, 1, function(x) names(which.max(table(x))))), ncol=1)

Upvotes: 1

Related Questions