首页 > 解决方案 > Purrr 映射多个模型以将结果存储在数据框中

问题描述

我有以下示例:

mtcars %>%
    group_split(cyl) %>%
    map(~lm(mpg ~ wt, data = .x)) %>%
    map_dbl(~.x$coefficients[[2]])

[1] -5.647025 -2.780106 -2.192438

我也想存储拦截,所以我认为这可能有效:

mtcars %>%
    group_split(cyl) %>%
    map(~lm(mpg ~ wt, data = .x)) %>%
    map_df(~.x$coefficients)

Error: Argument 1 must have names

但是我得到这个错误。我做错了什么,如何将两个系数存储在数据框中?

标签: rdplyrpurrr

解决方案


系数返回一个数字向量,我们可以将其更改为 dataframe 然后使用map_df.

library(tidyverse)

mtcars %>%
  group_split(cyl) %>%
  map(~lm(mpg ~ wt, data = .x)) %>%
  map_df(~.x$coefficients %>% t %>% as.data.frame)

#  (Intercept)      wt
#1      39.571 -5.6470
#2      28.409 -2.7801
#3      23.868 -2.1924

推荐阅读