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

Transforming dataset to have dates as rows instead of columns in R

I have a dataset of unemployment data for the EU countries like this:

Country    2021-08 2021-09 2021-10
Belgium    332     323     312
Bulgaria   162     157     152

What I want is to transform this dataset to get a table like this:

Date      Country    Unemployment
2021-08   Belgium    332
2021-08   Bulgaria   162
2021-09   Belgium    323
2021-09   Bulgaria   157
2021-10   Belgium    312
2021-10   Bulgaria   152

Can you help me how to do it?

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

Thank you in advance!

>Solution :

library(dplyr, tidyr)

df %>% 
  pivot_longer(-Country, names_to = "Date", values_to = "Unemployment") %>% 
  mutate(Date = sub("X(\\d{4})\\.(\\d{2})", "\\1-\\2", Date))
       Country  Date    Unemployment
  <chr>    <chr>          <int>
1 Belgium  2021-08          332
2 Belgium  2021-09          323
3 Belgium  2021-10          312
4 Bulgaria 2021-08          162
5 Bulgaria 2021-09          157
6 Bulgaria 2021-10          152
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