Suppose one wants to have the frequency table
as a data.frame
object, what is the best way to convert it? I tried some ideas and came up with a convoluted solution and I'm wondering if there is a better way.
First we generate some data:
set.seed(1)
test_df = data.frame(X = sample(0:1, 100, T),
Y = sample(0:1, 100, T))
p = table(test_df)
p2 = prop.table(p)
I'm interested in the prop.table()
output, but it applies equally to the frequency table
. It looks like this:
> p2
Y
X 0 1
0 28 18
1 34 20
as.data.frame()
works but returns the result in long format:
> as.data.frame(p2)
X Y Freq
1 0 0 28
2 1 0 34
3 0 1 18
4 1 1 20
as.matrix()
does nothing:
> class(as.matrix(p2))
[1] "table"
Finally, a convoluted method that works:
prop_table = as.data.frame(matrix(as.vector(p2), nrow = 2))
colnames(prop_table) = rownames(prop_table) = rownames(p2)
Output:
> prop_table
0 1
0 28 18
1 34 20
Better ideas?