Ruben
Ruben

Reputation: 493

How to calculate the mode of all rows or columns from a dataframe

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

Upvotes: 0

Views: 6024

Answers (1)

ghonke
ghonke

Reputation: 341

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)

Upvotes: 4

Related Questions