r - 与 dcast 相反

标签 r reshape

<分区>

想法是将频率表转换为 geom_density 可以处理的内容 (ggplot2)。

从频率表开始

> dat <- data.frame(x = c("a", "a", "b", "b", "b"), y = c("c", "c", "d", "d", "d"))
> dat
  x y
1 a c
2 a c
3 b d
4 b d
5 b d

使用dcast制作频率表

> library(reshape2)
> dat2 <- dcast(dat, x + y ~ ., fun.aggregate = length)
> dat2
  x y count
1 a c     2
2 b d     3

这怎么能逆转呢? melt 似乎不是答案:

> colnames(dat2) <- c("x", "y", "count")
> melt(dat2, measure.vars = "count")
  x y variable value
1 a c    count     2
2 b d    count     3

最佳答案

因为您可以使用任何聚合函数,所以在不知道如何反转聚合的情况下您将无法反转dcast(聚合)。

对于length,明显的逆是rep。对于 summean 之类的聚合,没有明显的逆(假设您没有将原始数据保存为属性)

一些反转length的选项

你可以使用ddply

library(plyr)
ddply(dat2,.(x), summarize, y = rep(y,count))

或者更简单的说

as.data.frame(lapply(dat2[c('x','y')], rep, dat2$count))

关于r - 与 dcast 相反,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18010069/

相关文章:

r - 结合几个 stat_function 行和原始数据点的图例

python - Tensorflow:feed_dict 的形状错误{}

MATLAB vec2mat 的 Python 等效代码

r - 在 R 中使用 reshape() 函数——从宽到长

在 R : rows to columns 中 reshape 数据框

r - 如何处理带有双标题的Excel文件

r - 从网状中的 python 导入

javascript - 通过R中的串扰使用选择框在R plotly图中选择默认值,使用静态html不 Shiny

linux - 无法在 Linux Mint 17 上安装 R 包

r - 仅更改ggplot2中热图上三角矩阵的颜色