0

I would like how to calculate the mode of all rows or columns from a matrix.

For example, I have:

seq <- c(1,2,3)
seq1 <- rep(seq, each=4)
mat1 <- matrix(seq1, 3)
mat1
rows <- c(1,2,3)
columns <- c("a", "b", "c", "d")
colnames (mat1) <- columns
rownames (mat1) <- rows
mat1
  a b c d
1 1 1 2 3
2 1 2 2 3
3 1 2 3 3

Now, I want to calculate the mode of each row and column. Thanks in advance

MrFlick
  • 195,160
  • 17
  • 277
  • 295
Ruben
  • 493
  • 4
  • 18
  • 2
    Perhaps this link helps http://stackoverflow.com/questions/2547402/standard-library-function-in-r-for-finding-the-mode – akrun Jan 22 '15 at 17:01
  • What have you tried? Have you looked at the `apply()` function? It's pretty useful for applying functions to rows/columns of a matrix. – MrFlick Jan 22 '15 at 17:01

1 Answers1

4

adapted from Is there a built-in function for finding the mode?

modefunc <- function(x){
    tabresult <- tabulate(x)
    themode <- which(tabresult == max(tabresult))
    if(sum(tabresult == max(tabresult))>1) themode <- NA
    return(themode)
}

#rows
apply(mat1, 1, modefunc)
#columns
apply(mat1, 2, modefunc)
Community
  • 1
  • 1
ghonke
  • 321
  • 3
  • 15