我没有看到任何关于我的问题。当我看到purrr的许多模型示例时,我想接下来该如何再次使用基于数据创建的模型?小代码会告诉你我在追求什么:
下面是许多模型的基本gapminder示例。
library(gapminder)
gapminder
by_country <- gapminder %>%
group_by(country, continent) %>%
nest()
country_model <- function(df) {
lm(lifeExp ~ year, data = df)
}
by_country <- by_country %>%
mutate(model = map(data, country_model))
by_country %>%
mutate(model_lag = lag(model))
# A tibble: 142 x 5
country continent data model model_lag
<fct> <fct> <list> <list> <list>
1 Afghanistan Asia <tibble [12 x 4]> <S3: lm> <lgl [1]>
2 Albania Europe <tibble [12 x 4]> <S3: lm> <S3: lm>
3 Algeria Africa <tibble [12 x 4]> <S3: lm> <S3: lm>
4 Angola Africa <tibble [12 x 4]> <S3: lm> <S3: lm>
5 Argentina Americas <tibble [12 x 4]> <S3: lm> <S3: lm>
6 Australia Oceania <tibble [12 x 4]> <S3: lm> <S3: lm>
7 Austria Europe <tibble [12 x 4]> <S3: lm> <S3: lm>
8 Bahrain Asia <tibble [12 x 4]> <S3: lm> <S3: lm>
9 Bangladesh Asia <tibble [12 x 4]> <S3: lm> <S3: lm>
10 Belgium Europe <tibble [12 x 4]> <S3: lm> <S3: lm>
# ... with 132 more rows
我的想法是,我可以用一个滞后的模型来预测数据,而不是用看到的数据来拟合值,我想做的是用这个滞后的模型来预测数据。我知道这是一个很糟糕的例子(为什么我要用阿富汗模型来描述阿尔巴尼亚),但我有数据嵌套在日期中,这是有意义的。这应该仍然是可复制的示例。那么,在这种格式中是否可以使用predict呢?
结果将是新的列“pred”[12x1],其中包含对新数据的预测,然后我可以使用数据取消预测,并在那里进行预测。