我试图在使用模型器的crossv_kfold的k折交叉验证数据集上拟合泊松回归模型,然后使用扫帚的增强函数得到预测。在我建模的数据中,我有一个我试图预测的计数,但它需要被曝光变量抵消。为了重现性,我已经包含了一个增强数据集来说明。
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.
答案 0 :(得分:1)
问题在于offset()
未被评估的方式和时间。我可以看到这是多么棘手,但解决方案很简单。
您只需要记住在等式中使用I()
进行转换。
例如:
warp_offset = crossv_kfold(warp, k = 10) %>%
mutate(model = map(train, ~ glm(breaks~ I(offset(log(total))) + wool*tension, ., family=poisson))) %>%
mutate(predicted = map2(model, test, ~ augment(.x, newdata = .y, predict.type= "response")))
不会抛出错误并产生预期效果。