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!
matrix() Function. as. matrix() function in R Programming Language is used to convert an object into a Matrix.
To convert a table into matrix in R, we can use apply function with as. matrix. noquote function.
table() Function. as. table() function in R Language is used to convert an object into a table.
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"
>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With