0

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.

Bandit King
  • 183
  • 10
  • Hi, have you tried to `unnest()` your tibble that contains multiple dataframes? To further help you, we might need to have a better idea of how your tibble looks like. Maybe use `dput(yourtibble)` and copy/paste the output in your question. – Paul Aug 13 '21 at 13:32
  • Does this answer your question? [unnest dataframe within dataframe R](https://stackoverflow.com/questions/62313519/unnest-dataframe-within-dataframe-r) – Paul Aug 13 '21 at 13:41
  • Excellent, thank you. Unnesting it worked well. I was doing my unnesting later in the process due to some other functions I'm running, but this gets it working. – Bandit King Aug 13 '21 at 13:46

1 Answers1

0

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')
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213