将data.frame中的列堆叠到R中的一列中 [英] stacking columns in data.frame into one column in R

查看:64
本文介绍了将data.frame中的列堆叠到R中的一列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法将data.frame中的列堆叠为一列。
现在我的数据看起来像这样:

I'm having trouble stacking columns in a data.frame into one column. Now my data looks something like this:

id   time    black   white   red 
a     1       b1      w1     r1
a     2       b2      w2     r2
a     3       b3      w3     r3
b     1       b4      w4     r4
b     2       b5      w5     r5
b     3       b6      w6     r6

我正在尝试转换data.frame,使其看起来像这样:

I'm trying to transform the data.frame so that it looks like this:

id   time  colour 
a     1     b1
a     2     b2
a     3     b3
b     1     b4
b     2     b5
b     3     b6
a     1     w1
a     2     w2
a     3     w3
b     1     w4
b     2     w5
b     3     w6
a     1     r1
a     2     r2
.     .     .
.     .     .
.     .     .

我想这个问题需要使用reshape软件包,但我不确定如何使用它可以将多个列堆叠在一个列下。有人可以为此提供帮助吗?

I'm guessing that this problem requires using the reshape package, but I'm not exactly sure how to use it to stack multiple columns under one column. Can anyone provide help on this?

推荐答案

重塑在这里融为一体:

library(reshape)
melt(x, id.vars=c('id', 'time'),var='color')






并使用 reshape2 (<< c $ c> reshape 的最新,更快的版本)的语法几乎相同。


And using reshape2 (an up-to-date, faster version of reshape) the syntax is almost identical.

帮助文件有一些有用的示例(请参见?melt melt.data.frame 的链接)。

The help files have useful examples (see ?melt and the link to melt.data.frame).

在您的情况下,以下内容将起作用(假设您的data.frame称为 DF

In your case, something like the following will work (assuming your data.frame is called DF)

library(reshape2)
melt(DF, id.var = c('id','time'), variable.name = 'colour')

这篇关于将data.frame中的列堆叠到R中的一列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆