简体   繁体   English

将data.frame中的列堆叠到R中的一列中

[英]stacking columns in data.frame into one column in R

I'm having trouble stacking columns in a data.frame into one column. 我在将data.frame中的列堆叠到一列时遇到问题。 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

I'm trying to transform the data.frame so that it looks like this: 我正在尝试转换data.frame,使其看起来像这样:

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
.     .     .
.     .     .
.     .     .

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. 我猜这个问题需要使用reshape包,但我不确定如何使用它来堆叠一列下的多个列。 Can anyone provide help on this? 任何人都可以提供帮助吗?

Here's melt from reshape: 这里是重塑的融化:

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

And using reshape2 (an up-to-date, faster version of reshape ) the syntax is almost identical. 使用reshape2 (最新的,更快的reshape版本),语法几乎完全相同。

The help files have useful examples (see ?melt and the link to melt.data.frame ). 帮助文件有一些有用的例子(参见?meltmelt.data.frame的链接)。

In your case, something like the following will work (assuming your data.frame is called DF ) 在您的情况下,类似下面的内容将起作用(假设您的data.frame称为DF

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

Since you mention "stacking" in your title, you can also look at the stack function in base R: 既然你在标题中提到“堆叠”,你也可以看一下基础R中的stack函数:

cbind(mydf[1:2], stack(mydf[3:5]))
#    id time values   ind
# 1   a    1     b1 black
# 2   a    2     b2 black
# 3   a    3     b3 black
# 4   b    1     b4 black
# 5   b    2     b5 black
# 6   b    3     b6 black
# 7   a    1     w1 white
# 8   a    2     w2 white
# 9   a    3     w3 white
# 10  b    1     w4 white
# 11  b    2     w5 white
# 12  b    3     w6 white
# 13  a    1     r1   red
# 14  a    2     r2   red
# 15  a    3     r3   red
# 16  b    1     r4   red
# 17  b    2     r5   red
# 18  b    3     r6   red

If the values in the "black", "white", and "red" columns are factor s, you'll need to convert them to character values first. 如果“黑色”,“白色”和“红色”列中的factorfactor s,则需要先将它们转换为character值。

cbind(mydf[1:2], stack(lapply(mydf[3:5], as.character)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM