问题描述
我尝试根据 Wickham 和 Grolemund (https://r4ds.had.co.nz/) 所著的“R for Data Science”一书中的第 20 章“许多带有 purrr 和 broom 的模型”计算大量泊松回归的逐步选择。然而,使用这种方法,计算模型缺乏有意义的名称,这在应用阶跃函数时似乎是有问题的。下面是一个可重现的示例。
library(tidyverse)
library(gapminder)
# Create tibble with variables and models for each corresponding country
by_country <- gapminder %>%
group_by(country,continent) %>%
nest()
# model-fitting function:
country_model <- function(df) {
lm(lifeExp ~ year + pop + gdpPercap,data = df)
}
# apply country_model to each element:
by_country <- by_country %>%
mutate(model = map(data,country_model))
# Stepwise selection
step_select <- mutate(by_country,step_sel = map(model,step))
# This fails
# It works fine if applied to individually calculated models (in this case for Germany),but not if you extract the same model from the tibble
# Individually calculated model
ge <- filter(gapminder,country == "Germany")
ge_mod <- lm(lifeExp ~ year + pop + gdpPercap,data = ge)
step(ge_mod)
# Extract the same model from the tibble
tb_ge_mod <- by_country[[4]][[48]]
step(tb_ge_mod)
# The only difference I can spot between these models is the name of data,which is generic in the tibble,but specific in the individually calculated model:
ge_mod[["call"]]
tb_ge_mod[["call"]]
ge_mod[["call"]][["data"]]
tb_ge_mod[["call"]][["data"]]
# If you replace these names,it works.
tb_ge_mod[["call"]][["data"]] <- ge
tb_ge_mod[["call"]] <- lm(formula = lifeExp ~ year + pop + gdpPercap,data = ge)
step(tb_ge_mod)
但是,我没有找到自动调整名称的方法(无论如何,这只是一种解决方法)。那么,有没有办法在这里应用逐步选择?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)