Search code examples
rmatrixdata-conversion

any straightforward way to convert `table` to `matrix`?


I have a table tb, for example

tb <- table(mtcars[c("carb","cyl")])
> tb
    cyl
carb 4 6 8
   1 5 2 0
   2 6 0 4
   3 0 0 3
   4 0 4 6
   6 0 1 0
   8 0 0 1

where

> class(tb)
[1] "table"

I am wondering if there is a more straightforward way to convert tb from a table to matrix, i.e.,

mtb <- as.matrix(as.data.frame.matrix(tb))

such that

> mtb
  4 6 8
1 5 2 0
2 6 0 4
3 0 0 3
4 0 4 6
6 0 1 0
8 0 0 1

and

> class(mtb)
[1] "matrix"

This is what I did for the conversion, but I don't think this is straightforward due to using both as.matrix() and as.data.frame.matrix().

Appreciated in advance!


Solution

  • You can do:

    unclass(table(mtcars[c("carb","cyl")]))
    

    Check class:

    class(unclass(table(mtcars[c("carb","cyl")])))
    
    [1] "matrix"