How to create a dataframe from a list of dataframes but have the column names be the list of dataframes?

Viewed 37

I have this list of dataframes. Within the individual dataframes, they all have columns 'country' and '2009' because this is the data I choose to work with. How do I combine all these dataframes by country, using the dataframes' names as the columns of my single dataframe (the result)? I am providing a picture of what my list and the dataframes look like.

enter image description here

The outcome dataframe should have the columns of 'water', 'childMort', 'totalFertility', etc. with 2009 COMPLETE data (no nas or columns with no matching country) but the rows would be the countries like for example:

country         water          childMort      totalFertility     ...
Albania          91.4               13.30                1.65
Angola           50.4              120.00                6.16
Afghanistan      48.3               88.00                5.82

I tried using reduce like below:

country2009df %>% reduce(left_join)

but I get an error of

Error in `fn()`:
! join columns must be character vectors.

update: I tried using bind_rows and it gives me the countries, but also '2009' as another column which I do not want and the column names I do want are under column 'name'.

bind_rows(country2009df, .id='name')

         name                        country   2009
1       water                          Aruba  97.30
2       water                    Afghanistan  48.30
3       water                         Angola  50.40
4       water                        Albania  91.40
5       water                        Andorra 100.00
1 Answers

You can use data.table package:

library(data.table)
country2009df_binded <- rbindlist(
    l = lapply(
        X = names(country2009df),
        FUN = function(i)
        {
            res <- country2009df[[i]]
            res$what <- i
            return(res)
        }
    )
)
country2009df_binded <- dcast(data = country2009df_binded, formula = country ~ what, value.var = "2009")
Related