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
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
. . .
. . .
. . .
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?
Since you mention "stacking" in your title, you can also look at the
stack
function in base R:If the values in the "black", "white", and "red" columns are
factor
s, you'll need to convert them tocharacter
values first.Here's melt from reshape:
And using
reshape2
(an up-to-date, faster version ofreshape
) the syntax is almost identical.The help files have useful examples (see
?melt
and the link tomelt.data.frame
).In your case, something like the following will work (assuming your data.frame is called
DF
)