【问题标题】:Double nesting in the tidyversetidyverse 中的双重嵌套
【发布时间】:2023-03-11 17:31:01
【问题描述】:

使用 Wickhams 的 examples 介绍 R 中的 purrr 用于数据科学,我正在尝试创建一个双嵌套列表。

library(gapminder)
library(purrr)
library(tidyr)
gapminder
nest_data <- gapminder %>% group_by(continent) %>% nest(.key = by_continent) 

如何进一步嵌套国家/地区,以便 nest_data 包含 by_continent 和新级别的嵌套 by_contry,最终包含 tibble by_year?

此外,在为 gapminder 数据创建此数据结构后 - 您将如何从 bookchapter 为每个国家/地区运行回归模型示例?

【问题讨论】:

  • 在按大洲和国家分组后,您有什么理由不能简单地嵌套?这似乎更容易使用。如果你真的想要嵌套列表列,nest_data %&gt;% mutate(by_continent = map(by_continent, ~.x %&gt;% group_by(country) %&gt;% nest(.key = by_country))) 怎么样?
  • 感谢您的帮助。该结构只是尝试理解列表列的问题。你的命令就像一个魅力。但是,我不确定我是否理解为什么。我尝试了类似的东西,但只有〜。而不是 ~.x 。 x 是做什么的?此外,如果我现在想对每个国家/地区进行回归而不采用取消嵌套并在 by_country 中获得结果,该怎么做?
  • 我已经看到..xmap 中使用,但我通常使用.x,因为这是文档中的内容。也许 . 在这里因为 mutate 包装器而感到困惑?就从列中嵌套的小标题按国家/地区划分的模型而言,事情变得一团糟。我到了mutate(nested_again, models = map(by_continent, "by_country") %&gt;% at_depth(2, ~lm(lifeExp ~ year, data = .x)))

标签: r tidyr purrr


【解决方案1】:

我的解决方案,下面有一些解释。

library(gapminder)
library(purrr)
library(tidyr)
library(broom)

nest_data <- gapminder %>% group_by(continent) %>% nest(.key = by_continent) 

第一个问题是:如何将 by_country 嵌套在嵌套的 by_continent 中

@aosmith 在 cmets 上的出色解决方案

nested_again<-
nest_data %>% mutate(by_continent = map(by_continent, ~.x %>% 
                                          group_by(country) %>% 
                                          nest(.key = by_country)))
# Level 1
nested_again
# # A tibble: 5 × 2
# continent      by_continent
# <fctr>            <list>
#   1      Asia <tibble [33 × 2]>
#   2    Europe <tibble [30 × 2]>
#   3    Africa <tibble [52 × 2]>
#   4  Americas <tibble [25 × 2]>
#   5   Oceania  <tibble [2 × 2]>

# Level 2
nested_again %>% unnest %>% slice(1:2)
# # A tibble: 2 × 3
# continent     country        by_country
# <fctr>      <fctr>            <list>
#   1      Asia Afghanistan <tibble [12 × 4]>
#   2      Asia     Bahrain <tibble [12 × 4]>

第二个问题:如何在更深层次应用回归模型(我想将模型保存在 tibble 上)

@aosmith 的解决方案(我称之为 sol1)

sol1<-mutate(nested_again, models = map(by_continent, "by_country") %>%
         at_depth(2, ~lm(lifeExp ~ year, data = .x)))

sol1
# # A tibble: 5 × 3
# continent      by_continent      models
# <fctr>            <list>      <list>
#   1      Asia <tibble [33 × 2]> <list [33]>
#   2    Europe <tibble [30 × 2]> <list [30]>
#   3    Africa <tibble [52 × 2]> <list [52]>
#   4  Americas <tibble [25 × 2]> <list [25]>
#   5   Oceania  <tibble [2 × 2]>  <list [2]>

sol1 %>% unnest(models)
# Error: Each column must either be a list of vectors or a list of data frames [models]
sol1 %>% unnest(by_continent) %>% slice(1:2)
# # A tibble: 2 × 3
#   continent     country        by_country
#      <fctr>      <fctr>            <list>
# 1      Asia Afghanistan <tibble [12 × 4]>
# 2      Asia     Bahrain <tibble [12 × 4]>

解决方案正在做它应该做的事情,但没有简单的方法来按国家/地区过滤,因为该信息嵌套在第 2 级中。

我根据@aosmith对第一个问题的解决方案提出解决方案2:

sol2<-nested_again %>% mutate(by_continent = map(by_continent, ~.x %>% 
                  mutate(models = map(by_country, ~lm(lifeExp ~ year, data = .x) )) ))
sol2
# # A tibble: 5 × 2
#   continent      by_continent
#      <fctr>            <list>
# 1      Asia <tibble [33 × 4]>
# 2    Europe <tibble [30 × 4]>
# 3    Africa <tibble [52 × 4]>
# 4  Americas <tibble [25 × 4]>
# 5   Oceania  <tibble [2 × 4]>

sol2 %>% unnest %>% slice(1:2)
# # A tibble: 2 × 4
#   continent     country        by_country   models
#      <fctr>      <fctr>            <list>   <list>
# 1      Asia Afghanistan <tibble [12 × 4]> <S3: lm>
# 2      Asia     Bahrain <tibble [12 × 4]> <S3: lm>

sol2 %>% unnest %>% unnest(by_country) %>% colnames
# [1] "continent" "country"   "year"      "lifeExp"   "pop"      
# [6] "gdpPercap"

# get model by specific country
sol2 %>% unnest %>% filter(country == "Brazil") %$% models %>% extract2(1)
# Call:
#   lm(formula = lifeExp ~ year, data = .x)
# 
# Coefficients:
#   (Intercept)         year  
# -709.9427       0.3901

# summary with broom::tidy
sol2 %>% unnest %>% filter(country == "Brazil") %$% models %>%
  extract2(1) %>% tidy
#          term     estimate    std.error statistic      p.value
# 1 (Intercept) -709.9426860 10.801042821 -65.72909 1.617791e-14
# 2        year    0.3900895  0.005456243  71.49417 6.990433e-15

我们可以整理所有模型并保存在数据中以用于绘图或过滤

sol2 %<>% mutate(by_continent = map(by_continent, ~.x %>% 
        mutate(tidymodels = map(models, tidy )) ))

sol2 %>% unnest %>% unnest(tidymodels) %>% 
  ggplot(aes(country,p.value,colour=continent))+geom_point()+
  facet_wrap(~continent)+
  theme(axis.text.x = element_blank())

selc <- sol2 %>% unnest %>% unnest(tidymodels) %>% filter(p.value > 0.05) %>% 
  select(country) %>% unique %>% extract2(1)

gapminder %>% filter(country %in% selc ) %>%
  ggplot(aes(year,lifeExp,colour=continent))+geom_line(aes(group=country))+
  facet_wrap(~continent)

aaaaand,我们可以使用模型

m1 <- sol2 %>% unnest %>% slice(1) %$% models %>% extract2(1)

x <- sol2 %>% unnest %>% slice(1) %>% unnest(by_country) %>% select(year)

pred1 <- data.frame(year = x, lifeExp = predict.lm(m1,x))

sol2 %>% unnest %>% slice(1) %>% unnest(by_country) %>%
  ggplot(aes(year, lifeExp )) + geom_point() +
  geom_line(data=pred1)

在这种情况下,确实没有充分的理由使用这种双重嵌套(当然,除了学习如何使用它),但我在我的工作中发现了一个非常有价值的案例,特别是当你需要一个函数来工作时在第 3 级,按 1 级和 2 级分组,并保存在 2 级 - 当然,为此我们也可以在 1 级使用 for 循环,但这有什么乐趣;)我不太确定如何这个“嵌套”map 的性能与for 循环 + map 相比,但接下来我会对其进行测试。

基准测试

看起来差别不大

# comparison map_map with for_map
map_map<-function(nested_again){
nested_again %>% mutate(by_continent = map(by_continent, ~.x %>% 
  mutate(models = map(by_country, ~lm(lifeExp ~ year, data = .x) )) )) }

for_map<-function(nested_again){ for(i in 1:length(nested_again[[1]])){
  nested_again$by_continent[[i]] %<>%
  mutate(models = map(by_country, ~lm(lifeExp ~ year, data = .x) )) }}

res<-microbenchmark::microbenchmark(
  mm<-map_map(nested_again), fm<-for_map(nested_again) )

res
# Unit: milliseconds
#                         expr      min       lq     mean   median       uq      max neval cld
#  mm <- map_map(nested_again) 121.0033 144.5530 160.6785 155.2389 174.2915 240.2012   100   a
#  fm <- for_map(nested_again) 131.4312 148.3329 164.7097 157.6589 173.6480 455.7862   100   a

autoplot(res)

【讨论】:

    猜你喜欢
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 2021-02-03
    • 2019-05-21
    • 1970-01-01
    • 2013-12-28
    相关资源
    最近更新 更多