将 nest 和 map 与 mgcv gam 和 broom augment 结合使用
Using nest and map in combination with mgcv gam and broom augment
我正在尝试为分组数据框中的每个样本创建平滑样条。为此,我使用了嵌套和映射方法以及 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 对象 'year' 未找到
下面的示例代码
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
在较新的版本中,我认为它还需要 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)
虽然这行得通,但这并不是 return 所有列,因为 broom
的 0.5.6 版本是这样的,即 se.fit
、.resid
、.hat
、.sigma
和 .cooksd
。这只有 return 的 .fitted
列。
我正在尝试为分组数据框中的每个样本创建平滑样条。为此,我使用了嵌套和映射方法以及 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 对象 'year' 未找到
下面的示例代码
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
在较新的版本中,我认为它还需要 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)
虽然这行得通,但这并不是 return 所有列,因为 broom
的 0.5.6 版本是这样的,即 se.fit
、.resid
、.hat
、.sigma
和 .cooksd
。这只有 return 的 .fitted
列。