【问题标题】:Predicting from list using lapply使用 lapply 从列表中预测
【发布时间】:2021-02-23 10:32:39
【问题描述】:

我正在尝试使用 dplyr 和 lapply 估计一组模型。我估计一个概率回归,结果存储在一个列表中。然后我想使用预测函数来预测新数据集上的值。我的模型运行,但我得到零值作为结果。我做错了什么?

# Code from the original question
library(dplyr)

year <- rep(2014:2015, length.out=10000)
group <- sample(c(0,1,2,3,4,5,6), replace=TRUE, size=10000)
value <- sample(10000, replace=T)
female <- sample(c(0,1), replace=TRUE, size=10000)
smoker <- sample(c(0,1), replace=TRUE, size=10000)
dta <- data.frame(year=year, group=group, value=value, female=female, smoker=smoker)

# cut the dataset into list
table_list <- dta %>%
  group_by(year, group) %>%
  group_split()

# fit model per subgroup
model_list <- lapply(table_list, function(x) glm(smoker ~ female, data=x,
                                                 family=binomial(link="probit")))

# create new dataset where female =1
dat_new <- data.frame(dta[, c("smoker", "year", "group")], female=1) 

# cut into list
pred_list <- dat_new %>%
  group_by(year, group) %>%
  group_split()

# do prediction
pred2 <- Map(function(x, y) predict.glm(x, type = "response", newdata = y), 
             model_list, pred_list)

我得到的预测结果为零。为什么?

【问题讨论】:

    标签: r dplyr lapply glm predict


    【解决方案1】:

    您应该改为lapply 而不是model_list

    pred1 <- lapply(model_list, function(x) predict.glm(x, type = "response"))
    

    或者,如果您想传递数据,请使用Map

    pred2 <- Map(function(x, y) predict.glm(x, type = "response", newdata = y), 
              model_list, pred_list)
    

    【讨论】:

      猜你喜欢
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 2015-05-30
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多