问题 将类“table”的对象转换为R中的矩阵


我很难从类“table”的对象转换为矩阵:

我有一个分类变量(R中的一个因子),我正在使用它的计数。我把这个计数存储在一个表中:

my.table = table(my.dataframef$cat.variable)
class(my.table)
[1] "table"

在使用此表做一些条形图后,我想做一个分段的条形图,所以我需要以矩阵的形式提供这些信息。 这就是我正在做的,但它不会工作(元素的顺序不正确):

my.matrix = matrix(my.table, nrow = n.matrix.rows, ncol = n.matrix.cols)

通过手动将每个元素分配到其位置,我已经解决了2x2矩阵的问题:

my.matrix = matrix (c(my.table[4],my.table[3],my.table[2],my.table[1]),
        nrow=2,ncol=2)

我想知道是否有一种“自动方式”来做这个,因为更大的矩阵它变成了一个艰难的练习......

谢谢你的帮助,我很感激!


10291
2018-05-17 17:59


起源

你能提供一个 dput 你的矩阵? - David Arenburg
谢谢David,这是一个输入: structure(c(686L, 337L, 686L, 466L), .Dim = c(2L, 2L), .Dimnames = list( c("male(mnt)", "female(mnt)"), c("male(auth)", "female(auth)" ))) - Ignacio de Castro
此外,我已经意识到指数正在递减。我试过写: my.matrix = matrix (rev(my.table),nrow=2,ncol=2) 并且工作正常...... - Ignacio de Castro
对不起,我的意思是 dput 你的 table (在转换为矩阵之前) - David Arenburg
好的,就是这样: structure(c(466L, 686L, 337L, 686L), .Dim = 4L, .Dimnames = structure(list( c("f-f", "f-m", "m-f", "m-m")), .Names = ""), class = "table") 谢谢大卫! - Ignacio de Castro


答案:


您可以使用此方法将class属性更改为“matrix”:

# input table
tbl <- structure(c(466L, 686L, 337L, 686L), 
      .Dim = 4L,
      .Dimnames = structure(list( c("f-f", "f-m", "m-f", "m-m")),
      .Names = ""), class = "table")


attributes(tbl)$class <- "matrix" 
#alternative syntax: attr(tbl, "class") <- "matrix"
tbl
#f-f f-m m-f m-m 
#466 686 337 686 
#attr(,"class")
#[1] "matrix"

4
2018-05-17 20:22





好吧,如果你知道一个表是一个附加了额外类“table”的数组,那就不难了。你只是 unclass() :

> tab <- structure(c(686L, 337L, 686L, 466L), .Dim = c(2L, 2L), 
             .Dimnames = list( c("male(mnt)", "female(mnt)"), 
                               c("male(auth)", "female(auth)" )))
> tab
            male(auth) female(auth)
male(mnt)          686          686
female(mnt)        337          466
> (mat <- unclass(tab))
            male(auth) female(auth)
male(mnt)          686          686
female(mnt)        337          466
> class(mat)
[1] "matrix"
> 

7
2018-05-17 20:19