Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

Edit: 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

      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 oneliner for this. Thank you!

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading