简体   繁体   English

如何将此列表列表转换为 R 中的数据框?

[英]How to convert this list of lists of lists into data frame in R?

Suppose we have something that looks like:假设我们有这样的东西:

list of two months:

Jan
Feb

Then when you expand Jan and Feb, you see other lists (countries):然后,当您展开一月和二月时,您会看到其他列表(国家/地区):

Jan -> USA, UK, etc.
Fab -> USA, UK, etc.

Finally, each country is a list, containing two items.最后,每个国家都是一个列表,包含两个项目。 Eg opening USA in the Jan list:例如在 Jan 列表中打开 USA:

USA -> gdp, population

What I'm trying to do is achieve a data frame like so (numbers would just be the values in data):我想要做的是实现这样的数据框(数字只是数据中的值):

month country gdp    population
Jan   USA     number no.
Jan   UK      number no.
Feb   USA     number no.
Feb   UK      number no.

I tried bind_rows(list) , which doesn't quite work because the header becomes the countries and the columns are populated with numbers that no longer have their labels.我尝试bind_rows(list) ,但效果不太好,因为 header 成为国家,并且列中填充了不再有标签的数字。

Does anyone have any ideas?有没有人有任何想法?

Edit: dput() output:编辑: dput() output:

list(`Jan` = list(UK = list(date_value = "Jan", 
    country_code = "UK", gdp = 308L, pop = 0L)

Here is an option这是一个选项

library(purrr)
library(dplyr)
map_dfr(lst2, bind_rows)
# A tibble: 2 x 4
#  date_value country_code   gdp   pop
#  <chr>      <chr>        <int> <int>
#1 Jan        UK             308     0
#2 Jan        UK             308     0

data数据

lst2 <- list(Jan = list(UK = list(date_value = "Jan", country_code = "UK", 
    gdp = 308L, pop = 0L)), Feb = list(UK = list(date_value = "Jan", 
    country_code = "UK", gdp = 308L, pop = 0L)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM