r - 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
但是我得到这个错误。我做错了什么,如何将两个系数存储在数据框中?
解决方案
系数返回一个数字向量,我们可以将其更改为 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
推荐阅读
- open3d - Open3D,GLFW 错误。没有返回 GLXFBConfigs
- android - Flutter 运行:任务“:app:processDebugResources”执行失败
- c++ - C99和C++03中空指针定义的区别
- function - 带有闭包的 Haskell 字典功能
- python - 熊猫得到错误的结果时
数字,蟒蛇 - c - Makefile 不推荐使用的语法
- javascript - 反应人生游戏(点击太快时出错)
- python - 在 Python 中,为什么集合运算并集、交集和对称差之间的时间复杂度不同?
- mysql - MySQL:用一个查询选择第一个不属于帮派的成员?
- php - 来自数据库的单选按钮导航