首页 > 解决方案 > 从 tibble 拉取列表以获得整洁的数据

问题描述

我正在尝试处理我有一个 tibble 的数据,其中我有一个用于某些观察的 tibble 列表。我想从这个列表中提取数据,以便有一些整洁的数据。

这是一个简短的例子:

data_1 <- tibble(year = c(2015, 2016), 
                 pop = c(100, 200))

data_2 <- tibble(year = c(2015, 2016), 
                 pop = c(300, 500))

data_combined <- list(data_1, data_2)

x <- tibble(country = (c('1', '2')), 
            data = data_combined)

print(x)
# A tibble: 2 x 2
  country data            
  <chr>   <list>          
1 1       <tibble [2 x 2]>
2 2       <tibble [2 x 2]>

print(x$data)
[[1]]
# A tibble: 2 x 2
   year   pop
  <dbl> <dbl>
1  2015   100
2  2016   200

[[2]]
# A tibble: 2 x 2
   year   pop
  <dbl> <dbl>
1  2015   300
2  2016   500

我想要的是以下整洁的数据格式(我不介意它是 data.frame 还是 tibble):

  country year pop
        1 2015 100
        1 2016 200
        2 2015 300
        2 2016 500

我认为最简单的方法是返回列表,即y$data保留国家字段,然后调用:do.call(rbind)。我不知道如何做第一部分。

也许我把这一切都弄错了,这种格式的数据很有用。如果是这种情况,并且有一种方法可以有效地处理带有小标题列表的小标题,那么我会欢迎任何有关这方面的信息。

所有这一切的背景是我正在尝试处理此 API 生成的数据:https ://cran.r-project.org/web/packages/eia/eia.pdf 。API 被限制为每次调用只能生成 100 行。我假设出于这个原因,作者使用这种数据格式来允许人们为每一行获取更多数据。如果您想了解一般示例,请参见下文:

#load libraries
library("eia")
library("dplyr")

#set API key for the session
eia_set_key(key = "[YOUR_KEY_HERE]")

#select a variable of interest by looking through: eia_cats() -> eia_child_cats(2134384)
anth_production <- eia_cats(2134515) %>% #select data for Anthracite (as a list)
  .$childseries %>% #subset the childseries element of the list
  filter(units == "Million Metric Tons of Oil Equivalent") %>% #filter to only have MMTOe
  .$series_id #subset the IDs to use in the eia_series() call 

#call the eia_series() function of the API
anth_production_tibble <- eia_series(id = anth_production)

anth_production_tibble现在以与我在可重现示例中生成的相同格式出现。稍后我将编写一个函数来处理 100 行的限制。

标签: rtibble

解决方案


我们可以用unnest

library(tidyr)
librar(dplyr)
x %>%
   unnest(data)
# A tibble: 4 x 3
#  country  year   pop
#  <chr>   <dbl> <dbl>
#1 1        2015   100
#2 1        2016   200
#3 2        2015   300
#4 2        2016   500

推荐阅读