Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an object of class "table" to matrix in R

Tags:

r

matrix

I am having a hard time converting from an object of class "table" to a matrix:

I have a categorical variable (a factor in R) and I am using its counts. I have this counts stored in a table:

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

After using this table to do some barplots I want to do a segmented barplot and so I need this information in the form of a matrix. This is what I am doing, but it wont work (elements are not in the correct order):

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

I have solved my problem for a 2x2 matrix by mannually assigning each element to its position:

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

I was wondering if there is an "automatic way" to do this as with bigger matrix it becomes a tough exercise...

Thank you for your help, I appreciate it!

like image 296
Ignacio de Castro Avatar asked May 17 '15 17:05

Ignacio de Castro


People also ask

How do I turn a object into a matrix in R?

matrix() Function. as. matrix() function in R Programming Language is used to convert an object into a Matrix.

How do I turn a table into a matrix in R?

To convert a table into matrix in R, we can use apply function with as. matrix. noquote function.

How do I convert an object to a table in R?

table() Function. as. table() function in R Language is used to convert an object into a table.


1 Answers

Well, that's not hard if you know that a table is an array with the extra class "table" attached: You just 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"
> 
like image 165
Martin Mächler Avatar answered Oct 18 '22 16:10

Martin Mächler