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?

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

Leave a Reply