如何计算数据框中所有行或列的模式

时间:2015-01-22 16:58:56

标签: r

我想如何计算矩阵中所有行或列的模式。

例如,我有:

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

现在,我想计算每行和每列的模式。 提前致谢

1 个答案:

答案 0 :(得分:2)

改编自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)