0

This question was closed, but it is different than its predecessors as it concerns a time series and the answer provided is so convenient that I believe it will help many beginners who don't know how to use the arguments correctly for a time series.

How can I reshape my data frame so that it follows the structure of economics_long?

I.e. the goal is this structure:

      Date         Variable         Value
1967 - 07 - 01      pce             506.7
1967 - 07 - 01      pop          198712.0
1967 - 07 - 01      psavert          12.6

Currently my data looks like this:

      Date          pce        pop        psavert
1967 - 07 - 01     506.7     198712.0      12.6   
1967 - 08 - 01      ...        ...          ...

All variables are numerical and Date is...

 $ Date: Date, format: "1999-01-06"

I haven't tried any code because I don't know how to fill in the arguments. I tried to create new datasets and merge them by a factor, but that failed and I am sure there is a one-liner for this.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Joschi Nin
  • 37
  • 5
  • I don't get why the date column being of the `Date` class would change how the answers in the previous post work. If there's some reason it does, a [reproducible example](https://stackoverflow.com/q/5963269/5325862) is necessary here – camille May 17 '23 at 20:40

1 Answers1

1

Using package tidyr, there is the glorious function pivot_longer(df,cols=-Date), where df is the name of the dataset. -Dateindicates all will be turned into long except Date.

JMenezes
  • 1,004
  • 1
  • 6
  • 13