【问题标题】:reshaping by index with melt and acast用熔体和铸件按指数重塑
【发布时间】:2013-05-23 19:17:35
【问题描述】:

这应该是一个简单的练习,在 R 中使用 reshape2 包,但不知何故我没有看到它。

假设我有数据:

df <- data.frame(A = rnorm(4), B = rnorm(4))

看起来像:

       A          B

1  2.3729531 -0.9252266
2  0.9848229 -0.1152347
3  2.1234409  0.9035180
4 -0.5771637  1.2755104

long_form <- melt(df)

看起来像

  variable      value
1        A  2.3729531
2        A  0.9848229
3        A  2.1234409
4        A -0.5771637
5        B -0.9252266
6        B -0.1152347
7        B  0.9035180
8        B  1.2755104

如何将long_form 转换回df

我可以通过先添加另一列来做到这一点,

long_form = data.frame(id = c(1:4, 1:4), long_form) dcast(long_form, id ~ variable)

然后删除id列恢复df;但似乎我应该能够在不显式添加 id 列来索引复制 A 和 B 的情况下做到这一点。

【问题讨论】:

    标签: r reshape2


    【解决方案1】:

    你可以的

    dcast(melt(df), 1:4 ~ variable)
    

    有点短。

    【讨论】:

    • 不错。如果我不知道重复次数,是否有小于1:dim(subset(long_form, variable=="A"))[1] 的内容?
    • 你总是可以做一些简单的事情,比如dcast(long_form, seq_along(df[,1])~variable)[,-1]dcast(long_form, 1:(nrow(long_form)/length(unique(long_form$variable)))~variable)[,-1]
    • @Dinre 假设我们知道df,在这种情况下我们不需要逆变换。
    • 抱歉...键入时不小心按了 Enter...没有完成整个评论。
    • hmm.. 短一点:dcast(long_form, 1:table(long_form$variable)[1] ~ variable)
    猜你喜欢
    • 1970-01-01
    • 2017-06-24
    • 2012-12-20
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    相关资源
    最近更新 更多