【问题标题】:Using nest and map in combination with mgcv gam and broom augment结合使用 nest 和 map 与 mgcv gam 和 broom augment
【发布时间】:2020-12-25 12:06:17
【问题描述】:

我正在尝试为分组数据框中的每个样本创建平滑样条曲线。为此,我使用了嵌套和地图方法和 mgcv gam(遵循此示例 https://smu095.github.io/2019/02/16/2019-02-16-tidytuesday-fitting-multiple-time-series-models-using-purrr/)。

运行游戏后,我想使用 broom::augment 来提取拟合数据并计算置信区间。

此代码使用 broom 0.5.6 工作,但使用新的 broom 0.7 版本会引发错误。 broom::tidy 和 broom:glance 仍然可以使用这种格式,但扩充停止时出现“错误:mutate() 输入 augment_spline 出现问题。 未找到 x 对象“年份””

下面的示例代码

library(tidyverse)
library(dslabs)

#Use the gapminder dataset that comes with dslabs as an example
glimpse(gapminder)

gapminder_nest <- gapminder %>% 
  group_by(country) %>% 
  nest()%>%
  mutate(splined =map(data, ~mgcv::gam(population ~ s(year, k=5, bs="tp"), data=.x))) %>%
  mutate(augment_spline= map(splined, broom::augment))%>%
  unnest(augment_spline)%>%
  dplyr::select(country, population,.fitted,.se.fit)

如果使用 broom 0.5.6,运行相同的代码

devtools::install_version("broom", version = "0.5.6", repos = "http://cran.us.r-project.org")

我能找到的所有在线教程都提供了似乎无法使用 broom 0.7 工作的类似代码

【问题讨论】:

    标签: r spline gam mgcv broom


    【解决方案1】:

    在较新的版本中,我认为它还需要 newdata 参数中的数据。您可以使用 map2 将数据作为单独的参数传递。

    library(tidyverse)
    library(dslabs)
    
    gapminder_nest <- gapminder %>% 
      group_by(country) %>% 
      nest()%>%
      mutate(splined = map(data, ~mgcv::gam(population ~ s(year, k=5, bs="tp"), data=.x))) %>%
      mutate(augment_spline = map2(splined, data, ~broom::augment(.x, newdata = .y))) %>%
      unnest(augment_spline)
    

    虽然这可行,但这并不像broom 的0.5.6 版本那样返回所有列,即se.fit、.resid、.hat、.sigma 和.cooksd。这只返回.fitted 专栏。

    【讨论】:

    • 谢谢。这非常有效,现在我将了解 map2。将 se_fit = TRUE 添加到增广调用也返回了 .se.fit 列
    猜你喜欢
    • 1970-01-01
    • 2020-03-21
    • 2016-01-07
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 2021-07-31
    相关资源
    最近更新 更多