R table by matrix row

后端 未结 4 1335
一向
一向 2020-12-31 06:01

For a matrix (as.matrix), how can I generate a table where rows are equal to rows of the matrix?

>table(matrix)

and

&g         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-31 06:34

    I used apply too:

    t(apply(mat, 1, function(x) table(factor(x, levels = unique(sort(c(mat)))))))
    
    R > mat  = matrix(sample(1:8, 20, replace = T), 5, 4)
    R > mat
         [,1] [,2] [,3] [,4]
    [1,]    5    6    1    4
    [2,]    4    3    4    8
    [3,]    4    8    4    3
    [4,]    3    3    5    1
    [5,]    1    1    3    1
    R > t(apply(mat, 1, function(x) table(factor(x, levels = unique(sort(c(mat)))))))
         1 3 4 5 6 8
    [1,] 1 0 1 1 1 0
    [2,] 0 1 2 0 0 1
    [3,] 0 1 2 0 0 1
    [4,] 1 2 0 1 0 0
    [5,] 3 1 0 0 0 0
    

提交回复
热议问题