查找grouped_by的线性模型的预测

时间:2019-10-18 19:15:34

标签: r dplyr broom

我想基于适合训练数据集的模型来获取预测值。我以前已经做过,但是现在我有了一个分组因子,这使我不满意。我想根据每种环境的种群预测生物量。

library(tidyverse)

fit_mods<-df %>%
  group_by(environ) %>%
  do(model = lm(biomass ~ poly(population, 2), data = .))

最终,我将要找出哪个种群的生物量最大。通常,我会通过创建一个网格并在新值上运行模型并找到最大值来做到这一点,但我对如何使用分组方法一无所知。常用方式:

min_pop <- min(df$population)
max_pop <- max(df$population)

grid_pop <- expand.grid(new = (seq(from = min_pop,
                                   to = max_pop, 
                                   length.out = 1000)),
                        environ = c("A", "B"))  

 #This is what I did with ungrouped data, but doesn't work now.
 pred_pop <- predict(object = fit_mods, 
                newdata = grid_pop,
                interval = "predict")  

以下是一些虚拟数据:

  df <- as.data.frame(list(environ = c("a", "a", "a", "a", "a", "b", "b", "b", "b", "b"),
   population = c(2, 3, 4, 5, 6, 3, 4, 5, 6, 7), 
   biomass = c(1, 2.2, 3.5, 4.1, 3.8, 2.5, 3.6, 4.3, 5.2, 5.1)), class = "data.frame")

1 个答案:

答案 0 :(得分:1)

通过tidyverse many models方法,您可以通过以下方式进行操作:

library(tidyverse)

   fit_mods <- df %>%
     nest(-environ) %>% 
     mutate(models = map(data, ~ lm(biomass ~ poly(population, 2), data = .x)),
         min_pop = map_dbl(data, ~ pull(.x, population) %>% min),
         max_pop = map_dbl(data, ~ pull(.x, population) %>% max),
         new = map2(min_pop, max_pop, ~ tibble(population = seq(from = .x,
                                                to = .y, 
                                                length.out = 1000))),
         pred = map2(models,
                     new,
                     ~ predict(object = .x,
                               newdata = select(.y,population),
                               interval = "predict")))