R-Count并逐行列出最大计数

时间:2013-08-13 02:13:32

标签: r max

我有一个矩阵:

count <- matrix(c("a","a","a","b","b","i","i","b","a","a","g","i","a","g","g","g"),ncol=4,byrow=TRUE)

    [,1] [,2] [,3] [,4]
[1,]  a    a    a   b
[2,]  b    i    i   b
[3,]  a    a    g   i
[4,]  a    g    g   g

我想找到每行中出现最大次数的值,并将这些值分配给另一列,如下所示:

    [,1] [,2] [,3] [,4] [,count]
[1,]  a    a    a   b      a
[2,]  b    i    i   b      b & i
[3,]  a    h    h   i      h
[4,]  a    g    g   g      g 

我尝试使用apply(count,1,max),但没有成功。

2 个答案:

答案 0 :(得分:5)

您的输入和输出数据不匹配,但我认为这就是您所追求的:

count <- matrix(c("a","a","a","b","b","i","i","b",
                  "a","a","g","i","a","g","g","g"),
                ncol = 4, byrow = TRUE)
count
#      [,1] [,2] [,3] [,4]
# [1,] "a"  "a"  "a"  "b" 
# [2,] "b"  "i"  "i"  "b" 
# [3,] "a"  "a"  "g"  "i" 
# [4,] "a"  "g"  "g"  "g"    

cbind(count,
      apply(count, 1, function(x) {
        z <- table(x)
        paste(names(z)[z == max(z)], collapse = " & ")
      }))
#      [,1] [,2] [,3] [,4] [,5]   
# [1,] "a"  "a"  "a"  "b"  "a"    
# [2,] "b"  "i"  "i"  "b"  "b & i"
# [3,] "a"  "a"  "g"  "i"  "a"    
# [4,] "a"  "g"  "g"  "g"  "g"  

答案 1 :(得分:-1)

你这个: cbind(count,apply(count,1,myfun&lt; -function(x){a&lt; -table(x); b&lt; -rownames(a)[a == max(a)]; b&lt; -paste(b, collapse =“&amp;”); return(b)}))