I have a data frame like this:
id y1 y2 y3 y4
--+--+--+--+--
a |12|13|14|
b |12|18| |
c |13| | |
d |13|14|15|16
I want to reshape in such a way that I end with two columns. The above example would then become:
id from to
--+----+---
a |12 |13
a |13 |14
a |14 |
b |12 |18
b |18 |
c |13 |
d |13 |14
d |14 |15
d |15 |16
Each id
has a 'from' and a 'to' per pair of year values.
Does anybody know of an easy way to do this? I tried using reshape2
. I also looked at Combine Multiple Columns Into Tidy Data but I think my case is different.
You can use
lapply
to loop over the pairs of columns andrbind
to union them:A solution uses
dplyr
andtidyr
.dt2
is the final output.In base R,
stack
and shift everything back one row in each group. Using @ycw's example data,dt
:In the world of
data.table
, the same logic applies.melt
, thenshift
by=
id: