r语言 - 在嵌套数据帧内应用 purrr::map() 时出现问题



我正在研究 Hadley Wickham 的R for Data Sciencehttps://r4ds.had.co.nz/many-models.html 的第 25 章"许多模型",但是我在 25.2.2 中重新创建示例时遇到了问题。

这是我到目前为止所拥有的(以及有效的方法(:

require(gapminder); require(tidyverse); require(broom); require(modelr)
by_country <- gapminder %>% group_by(country,continent) %>% nest()
head(by_country)
# A tibble: 6 x 3
country     continent data             
<fct>       <fct>     <list>           
1 Afghanistan Asia      <tibble [12 × 4]>
2 Albania     Europe    <tibble [12 × 4]>
3 Algeria     Africa    <tibble [12 × 4]>
4 Angola      Africa    <tibble [12 × 4]>
5 Argentina   Americas  <tibble [12 × 4]>
6 Australia   Oceania   <tibble [12 × 4]>

然后定义要应用于每个国家/地区数据集的lm()

country_model <- function(df) {
lm(lifeExp ~ year, data = df)
}

然后下一行不起作用:

by_country <- by_country %>%
mutate(model = map(data,country_model))

带有错误消息

Error in eval(predvars, data, env) : object 'lifeExp' not found 

尽管在我看来,我写的东西与哈德利章节中出现的内容相同。

我不确定这是否是曾经有效的最近问题,因为其他人显然对该示例有问题:https://github.com/hadley/r4ds/issues/766(没有解决方案(

任何帮助将不胜感激!

您不需要重新定义"by_country"两次。

country_model <- function(df) {
lm(lifeExp ~ year, data = df)
}
by_country <- gapminder %>% 
group_by(country,continent) %>% 
nest()%>%
mutate(model = map(data,country_model))

group_by + nest 组合可以用 nest_by 替换,唯一不同的是结果是按行分组的,因此您需要将函数放在列表中。像这样:

results <- gapminder %>% 
nest_by(continent, country) %>% 
mutate(model = list(lm(lifeExp ~ year, data = data)))

最新更新