r - 将熔化的 table 变回 table

标签 r melt

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)的结果进行比较。唯一的区别是“数字”列的名称(valueFreq)。

通过执行 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 形式使用交叉表,或者更好地使用 tidyversetibble > 更可取!

关于r - 将熔化的 table 变回 table ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50764178/

相关文章:

python - 如何用小时列融化 `pandas.DataFrame` 并将它们划分为 15 分钟间隔

r - 对 R data.table 的每一列进行排序

r - 在 R 中 NA == NA?

r - 使用 dplyr 仅对某些列执行操作

r - 从 R 中的文件夹堆叠光栅图像

r - 如何从psych包中describeBy的输出中排除变量?

r - 如何在带有变量的 tidyr 中使用 gather_

python - Pandas - 基于列名称中的多个属性融化、堆叠、 reshape 或 MultiIndex 数据框列

reshape 1 列中的值并附加到现有列名

python - 融化一堆多索引列,同时保留单个 'index' 列