[英]How do you do predict.gam on many models nested within tibbles?
我一直在關注https://r4ds.had.co.nz/many-models.html為每一行創建一個帶有單獨 GAM 的小標題。 數據列列出了用於生成 GAM 的數據。 現在我在嘗試使用 predict.gam function 生成具有預測值的新列時遇到了麻煩。
# A tibble: 2,157 x 3
# Groups: Site [2,157]
Site data model
<fct> <list> <list>
1 Abana Rock North 1 <tibble [7 x 6]> <gam>
2 Abana Rock North 2 <tibble [7 x 6]> <gam>
3 Abana Rock South 1 <tibble [7 x 6]> <gam>
4 Abana Rock South 2 <tibble [7 x 6]> <gam>
5 Ampa Marker East <tibble [7 x 6]> <gam>
6 Ampa Marker West <tibble [7 x 6]> <gam>
7 Ampa Patches Southwest 1 <tibble [7 x 6]> <gam>
8 Ampa Patches Southwest 2 <tibble [7 x 6]> <gam>
9 Brunei Patches 1 <tibble [7 x 6]> <gam>
10 Brunei Patches 2 <tibble [7 x 6]> <gam>
# ... with 2,147 more rows
# A tibble: 7 x 6
Country Location Year Population100km
<fct> <fct> <dbl> <int>
1 Brunei Inshore Brunei 1990 431102
2 Brunei Inshore Brunei 1995 492958
3 Brunei Inshore Brunei 2000 545008
4 Brunei Inshore Brunei 2005 602691
5 Brunei Inshore Brunei 2010 660197
6 Brunei Inshore Brunei 2015 715266
7 Brunei Inshore Brunei 2020 766133
到目前為止的代碼如下:
data <- rawdata %>%
group_by(Site) %>%
nest()
model_function <- function(df) {
gam(Population100km ~ Year, data = df)
}
models <- data %>%
mutate(model = map(data, mode_function))
years <- data.frame(Year=1990:2020)
現在我基本上嘗試為每個 model 運行以下命令,並使用 mutate 將其保存為另一列。
predict.gam(models$model, predict.years)
任何幫助,將不勝感激。 謝謝!
您應該能夠對預測使用類似的語法。 我在這里使用了 gapminder 使其可重現。
library(tidyverse)
library(mgcv)
#> Loading required package: nlme
#>
#> Attaching package: 'nlme'
#> The following object is masked from 'package:dplyr':
#>
#> collapse
#> This is mgcv 1.8-31. For overview type 'help("mgcv-package")'.
rawdata <- gapminder::gapminder
data <- rawdata %>%
group_by(country) %>%
nest()
years <- data.frame(year=1990:2020)
models <- data %>%
mutate(
model = map(data, ~ gam(lifeExp ~ year, data = .x)),
predicted = map(model, ~ predict(.x, newdata = years))
)
unnest(models, predicted)
#> # A tibble: 4,402 x 4
#> # Groups: country [142]
#> country data model predicted
#> <fct> <list> <list> <dbl>
#> 1 Afghanistan <tibble [12 × 5]> <gam> 40.4
#> 2 Afghanistan <tibble [12 × 5]> <gam> 40.6
#> 3 Afghanistan <tibble [12 × 5]> <gam> 40.9
#> 4 Afghanistan <tibble [12 × 5]> <gam> 41.2
#> 5 Afghanistan <tibble [12 × 5]> <gam> 41.5
#> 6 Afghanistan <tibble [12 × 5]> <gam> 41.7
#> 7 Afghanistan <tibble [12 × 5]> <gam> 42.0
#> 8 Afghanistan <tibble [12 × 5]> <gam> 42.3
#> 9 Afghanistan <tibble [12 × 5]> <gam> 42.6
#> 10 Afghanistan <tibble [12 × 5]> <gam> 42.8
#> # … with 4,392 more rows
由代表 package (v0.3.0) 於 2020 年 4 月 10 日創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.