【问题标题】:How to calculate the mode of all rows or columns from a dataframe如何计算数据框中所有行或列的模式
【发布时间】:2015-03-21 13:56:35
【问题描述】:

我想知道如何计算矩阵中所有行或列的众数。

例如,我有:

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

现在,我想计算每一行和每一列的众数。 提前致谢

【问题讨论】:

标签: r


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多