Search code examples
rdataframetime-seriesreshape

How can I reshape my data.frame from wide to long using a Date variable?


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.


Solution

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