我正在尝试使用 modelr 的 crossv_kfold 在 k 折交叉验证数据集上拟合泊松回归模型,然后使用 broom 的增强函数进行预测。在我正在建模的数据中,我有一个我试图预测的计数,但它需要被一个曝光变量抵消。为了重现性,我已经包含了一个增强的数据集来说明。
library(tidyverse)
library(modelr)
non_breaks = rpois(dim(warpbreaks)[1],20)
warp = warpbreaks %>%
mutate(total = breaks + non_breaks)
因此,在此示例中,我将对给定分类变量的中断次数进行建模,并通过总曝光量来抵消。我发现如果我的模型中不包含偏移项,那么一切都很好:
library(broom)
warp_no_offset = crossv_kfold(warp, k = 10) %>%
mutate(model = map(train, ~ glm(breaks~ wool*tension, ., family=poisson))) %>%
mutate(predicted = map2(model, test, ~ augment(.x, newdata = .y, predict.type= "response")))
但是,如果我包括一个抵消项:
warp_offset = crossv_kfold(warp, k = 10) %>%
mutate(model = map(train, ~ glm(breaks~ offset(log(total)) + wool*tension, ., family=poisson))) %>%
mutate(predicted = map2(model, test, ~ augment(.x, newdata = .y, predict.type= "response")))
它抛出错误:
Error in mutate_impl(.data, dots) :
Evaluation error: arguments imply differing number of rows: 5, 49.