1

I have a data frame:

>head(df, 5)
                 date  time loads unloads
1 2018-04-02 01:00:00 01:00   100    3462
2 2018-04-02 02:00:00 02:00    35    2031
3 2018-04-02 03:00:00 03:00     0    1734
4 2018-04-02 04:00:00 04:00  1908    2499
5 2018-04-02 05:00:00 05:00   333    3069

I want to merge the values of both the loads and unloads columns into a single column, and merely repeat the value in date for each new row and list the type in another column.

To help explain, each row would be split into two rows and the resulting data frame would look like this:

                 date  time  count    type
1 2018-04-02 01:00:00 01:00    100    load
2 2018-04-02 01:00:00 01:00   3462  unload
3 2018-04-02 02:00:00 02:00     35    load
4 2018-04-02 02:00:00 02:00   2031  unload

and so on.

How can this be done?

Mus
  • 7,290
  • 24
  • 86
  • 130

1 Answers1

5

We can use gather from tidyr to reshape it to 'long' format

library(tidyr)
gather(df, count, type, loads:unloads)
akrun
  • 874,273
  • 37
  • 540
  • 662