'Converting an object of class "table" to matrix in R
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!
Solution 1:[1]
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"
>
Solution 2:[2]
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
Solution 3:[3]
> table(letters[1:3], 1:3)
1 2 3
a 1 0 0
b 0 1 0
c 0 0 1
> class(table(letters[1:3], 1:3))
[1] "table" # is a table
> class(as.matrix(table(letters[1:3], 1:3))) # still a table
[1] "table"
> as.data.frame(table(letters[1:3], 1:3)) # doesn't work
Var1 Var2 Freq
1 a 1 1
2 b 1 0
3 c 1 0
4 a 2 0
5 b 2 1
6 c 2 0
7 a 3 0
8 b 3 0
9 c 3 1
> as.data.frame.matrix(table(letters[1:3], 1:3)) # works
1 2 3
a 1 0 0
b 0 1 0
c 0 0 1
> class(as.matrix(as.data.frame.matrix(table(letters[1:3], 1:3)))) # to your goal
[1] "matrix"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Martin Mächler |
| Solution 2 | |
| Solution 3 | foehn |
