Titanic是R中的一个数据集,其类别为“table”。
dim(Titanic)
表明它是 4 维的。
现在,如果我这样做
x <- Titanic
y <- melt(x)
y 看起来像一个二维数据框。 我的问题是,如何将 y 改回 x?我能得到的最接近的是
z <- table(y)
但是 z 是 5 维的。
有人可以帮助我吗?
最佳答案
关于 reshape2::melt(Titaninc)
的结果,没有太多 melt
内容。与as.data.frame(Titanic)
的结果进行比较。唯一的区别是“数字”列的名称(value
与 Freq
)。
通过执行 class(Titanic)
和 ?table
,您会发现 Titanic
是来自 的数据类型>table()
函数。在文档中,您还可以注意到有 xtabs
,基于公式的制表界面。在 xtabs
文档中,formula
参数说
... 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, ...
这给你留下了一个简单的
dt <- as.data.frame(Titanic)
xtabs( Freq ~ Class + Sex + Age + Survived, data = dt )
重建表
类数据,如果您需要它作为其他包的输入。
添加我的两分钱,以简单的二维 data.frame
形式使用交叉表,或者更好地使用 tidyverse
的 tibble
> 更可取!
关于r - 将熔化的 table 变回 table ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50764178/