Titanic is a data set in R whose class is "table".
dim(Titanic)
tells it is 4-dimensional.
Now, if I do
x <- Titanic
y <- melt(x)
y looks like a 2-dimensional data frame. My question is, how can I change y back to x? The closest I could get was by
z <- table(y)
But then z is 5-dimensional.
Could anyone help me?
There is not much melt
ed about the result of reshape2::melt(Titaninc)
. Compare with the result of as.data.frame(Titanic)
. The only difference is the name of 'numbers' column (value
vs Freq
).
By doing class(Titanic)
and ?table
you find out that the Titanic
is type of data that comes out of the table()
function. In the documentation you can also notice that there is xtabs
, formula based interface to tabulation. In xtabs
docs, formula
argument says
... On the left hand side, one may optionally give a vector or a matrix of counts; in the latter case, the columns are interpreted as corresponding to the levels of a variable. This is useful if the data have already been tabulated, ...
Which leaves you with a simple
dt <- as.data.frame(Titanic)
xtabs( Freq ~ Class + Sex + Age + Survived, data = dt )
to reconstruct the table
classed data, should you ever need it for some other package as input.
Tto add my two cents, working with a crosstab in a form of a simple two dimensional data.frame
or better a tibble
from tidyverse
is much more advisable!