Converting an object of class "table" to matrix in R
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"
>
This approach works for me:
tab <- table(sample(LETTERS, 1e4, replace = T), sample(letters, 1e4, replace = T))
class(tab) # table
mat <- matrix(as.numeric(tab), nrow = nrow(tab), ncol = ncol(tab))
class(mat) # matrix
all(mat == tab) # TRUE
You can use this approach to change the class attribute to "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"