繁体   English   中英

在嵌套的 dataframe 中应用 purrr::map() 问题

[英]Issue applying purrr::map() inside nested dataframe

I'm working through chapter 25 "Many Models" of Hadley Wickham's R for Data Science https://r4ds.had.co.nz/many-models.html , however I'm running into issues in recreating the examples in 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)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM