1

我有一个矩阵:

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)但没有成功。

4

2 回答 2

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"  
于 2013-08-13T02:27:58.963 回答
-1

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

于 2013-08-13T03:20:24.177 回答