How to convert a table to a data frame
If you are using the tidyverse, you can use
as_data_frame(table(myvector))
to get a tibble (i.e. a data frame with some minor variations from the base class)
While the results vary in this case because the column names are numbers, another way I've used is data.frame(rbind(mytable))
. Using the example from @X.X:
> freq_t = table(cyl = mtcars$cyl, gear = mtcars$gear)
> freq_t
gear
cyl 3 4 5
4 1 8 2
6 2 4 1
8 12 0 2
> data.frame(rbind(freq_t))
X3 X4 X5
4 1 8 2
6 2 4 1
8 12 0 2
If the column names do not start with numbers, the X
won't get added to the front of them.
Short answer: using as.data.frame.matrix(mytable)
, as @Victor Van Hee suggested.
Long answer: as.data.frame(mytable)
may not work on contingency tables generated by table()
function, even if is.matrix(your_table)
returns TRUE
. It will still melt you table into the factor1 factor2 factori counts
format.
Example:
> freq_t = table(cyl = mtcars$cyl, gear = mtcars$gear)
> freq_t
gear
cyl 3 4 5
4 1 8 2
6 2 4 1
8 12 0 2
> is.matrix(freq_t)
[1] TRUE
> as.data.frame(freq_t)
cyl gear Freq
1 4 3 1
2 6 3 2
3 8 3 12
4 4 4 8
5 6 4 4
6 8 4 0
7 4 5 2
8 6 5 1
9 8 5 2
> as.data.frame.matrix(freq_t)
3 4 5
4 1 8 2
6 2 4 1
8 12 0 2
I figured it out already:
as.data.frame.matrix(mytable)
does what I need -- apparently, the table needs to somehow be converted to a matrix in order to be appropriately translated into a data frame. I found more details on this as.data.frame.matrix() function for contingency tables at the Computational Ecology blog.