在嵌套数据帧内应用Purrr::Map()时出现问题 [英] Issue applying purrr::map() inside nested dataframe

查看:0
本文介绍了在嵌套数据帧内应用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(没有解决方案)

如有任何帮助,不胜感激!

推荐答案

GROUP_BY+NEST组合可以替换为NEST_BY,唯一不同的是结果是按行分组的,因此您需要将函数放在列表中。大概是这样的:

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

这篇关于在嵌套数据帧内应用Purrr::Map()时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆