R表按矩阵行 [英] R table by matrix row

查看:93
本文介绍了R表按矩阵行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于矩阵(如矩阵),如何生成行等于矩阵行的表?

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

>table(matrix)

>hist(matrix)

显示矩阵中每个唯一数据值的累积总和,但是我想要一个表,其中行与每个矩阵行的值相同,而表列是矩阵中每个唯一数据值的总和.

show the cumulative sum for each unique data value in the matrix, but I would like a table where rows are the same value as each matrix row, and table columns are the sum occurrence of each unique data value in the matrix.

示例矩阵:

   1  2  3  4 
a  5  5  4  6    
b  5  5  5  5     
c  8  7  6  6   
d  2  6  6  6     
e  7  7  5  4      

所需的输出表:

   2  4  5  6  7  8
a  0  1  2  1  0  0
b  0  0  4  0  0  0
c  0  0  0  2  1  1
d  1  0  0  3  0  0
e  0  1  1  0  2  0

推荐答案

一种替代方法是将matrix转换为长的data.frame(使用stack),此时您可以轻松地使用table:

One alternative is to convert your matrix to a long data.frame (using stack), at which point you can easily use table:

这是您的数据:

mymat <- structure(c(5L, 5L, 8L, 2L, 7L, 5L, 5L, 7L, 6L, 7L, 4L, 5L, 6L, 
            6L, 5L, 6L, 5L, 6L, 6L, 4L), .Dim = c(5L, 4L), .Dimnames = list(
              c("a", "b", "c", "d", "e"), c("1", "2", "3", "4")))

这是长data.frame的样子:

head(stack(data.frame(t(mymat))))
#   values ind
# 1      5   a
# 2      5   a
# 3      4   a
# 4      6   a
# 5      5   b
# 6      5   b

这是我们可以用来创建所需表的方法:

Here's how we can use that to create the table you want:

with(stack(data.frame(t(mymat))), table(ind, values))
#    values
# ind 2 4 5 6 7 8
#   a 0 1 2 1 0 0
#   b 0 0 4 0 0 0
#   c 0 0 0 2 1 1
#   d 1 0 0 3 0 0
#   e 0 1 1 0 2 0

这篇关于R表按矩阵行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆