【问题标题】:Purrr map over multiple models to store results in dataframePurrr 映射多个模型以将结果存储在数据框中
【发布时间】:2020-02-12 08:07:59
【问题描述】:

我有以下例子:

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

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

【问题讨论】:

    标签: r dplyr purrr


    【解决方案1】:

    系数返回一个数字向量,我们可以将其更改为数据框,然后使用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
    

    【讨论】:

    • 太棒了,谢谢,不知道我可以在地图中使用管道运算符 :)
    猜你喜欢
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多