My tibble contains multiple dataframes as follows:
cntry | df |
---|---|
south_africa | 8 variables |
angola | 8 variables |
ghana | 8 variables |
Each sub-dataframe (i.e. one of the variables referred to above) is as follows:
date | growth | external_financing |
---|---|---|
2020-01-01 | -1 | 0 |
2020-02-01 | -1 | 1 |
2020-03-01 | -2 | 1 |
How do I merge all the dataframes to have a column with the country to which that score relates? I would like a result as follows (clearly, some pivoting will also be required):
date | country | metric | score |
---|---|---|---|
2020-01-01 | south_africa | growth | 0 |
2020-02-01 | south_africa | growth | 1 |
2020-03-01 | south_africa | growth | 1 |
2020-01-01 | south_africa | external_financing | 0 |
2020-02-01 | south_africa | external_financing | 1 |
2020-03-01 | south_africa | external_financing | 1 |
And so on...with all the data in this long format.
You can try using unnest
and pivot_longer
-
library(dplyr)
library(tidyr)
data %>%
unnest(df) %>%
pivot_longer(cols = -c(cntry, date),
names_to = 'metric', values_to = 'score')