在purrr :: map之后使用新数据集从glm模型预测概率

时间:2019-07-05 03:48:10

标签: r loops purrr

我要用purrr::map代替r for loop,并用新的数据集预测概率。

使用for循环,我已经能够使用新的数据集获得不同子组的预测概率。我正在尝试使用purrr::map作为新的R用户重现相同的分析结果,但只是不确定在哪里可以找到相关的说明。

library(tidyverse)
data("mtcars")
newdata <- expand.grid(mpg = 10:34)
output <- setNames(data.frame(matrix(ncol = 3, nrow = 0)), 
              c("mpg", "am", "pr_1"))
for (i in c(0, 1)) { 
md_1 <- glm(vs ~ mpg, data = filter(mtcars, am == i), family ="binomial")
  pr_1 <- predict(md_1, newdata, type = "response")
  output_1 <- data.frame(newdata, am = i, pr_1)
  output <- bind_rows(output_1, output)
}
# Try purrr::map
my_predict<-mtcars %>% 
split(.$am) %>% 
map(~glm(vs~mpg, family = "binomial", data = .x)) 
# then? predict(my_predict, newdata, type="response") not working 

我期望一个新的数据集具有不同子组的预测概率,就像上面的for循环一样。

1 个答案:

答案 0 :(得分:2)

我们可以使用新的group_split根据组划分数据帧(am),然后使用map_df为每个组创建一个新模型,并基于此模型获得预测值。

library(tidyverse)

mtcars %>% 
  group_split(am) %>%
  map_df(~{
  model <- glm(vs~mpg, family = "binomial", data = .)
  data.frame(newdata,am = .$am[1], pr_1 = predict(model,newdata, type = "response"))
}) 

#   mpg am         pr_1
#1   10  0 0.0000831661
#2   11  0 0.0002519053
#3   12  0 0.0007627457
#4   13  0 0.0023071316
#5   14  0 0.0069567757
#6   15  0 0.0207818241
#7   16  0 0.0604097519
#8   17  0 0.1630222293
#9   18  0 0.3710934960
#10  19  0 0.6412638468
#.....