在purrr :: map_df之后如何使用映射向量添加列 [英] How to add a column using the mapping vector after purrr::map_df
本文介绍了在purrr :: map_df之后如何使用映射向量添加列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我以mtcars数据集为例来说明我的问题。我对每种圆柱体类型进行了线性回归,并使用map_df将所有模型结果汇总在一起。 (下面的代码和输出)。我要添加的另一列名为圆柱(cylinder)(4,4,6,6,8,8)。如何在map_df中做到这一点?当我添加参数.id ='cylinder'时,我只得到了1,1,2,2,3,3列。
I'm using the mtcars dataset as an example to illustrate my question. I ran linear regression on each cylinder type and put all model result together using map_df. (Code and output below). What I want to do is adding another column named 'cylinder' (4,4,6,6,8,8). How can I do that in map_df? When I add argument .id='cylinder', I only got a column as 1,1,2,2,3,3. Thanks a lot in advance.
library(purrr)
cyls <- c(4,6,8)
map_df(cyls, ~tidy(lm(hp~wt,data=mtcars %>% filter(cyl == .x))))
推荐答案
使用 set_names
应该做到
cyls %>%
set_names() %>%
map_df(., ~tidy(lm(hp~wt,data=mtcars %>% filter(cyl == .x))), .id = "cyls")
cyls term estimate std.error statistic
1 4 (Intercept) 69.204726 28.41355 2.43562436
2 4 wt 5.876308 12.09420 0.48587823
3 6 (Intercept) 187.273314 90.85245 2.06129062
4 6 wt -20.848451 28.98418 -0.71930440
5 8 (Intercept) 204.484626 78.77132 2.59592744
6 8 wt 1.182647 19.37501 0.06103983
p.value
1 0.03763378
2 0.63866393
3 0.09427827
4 0.50415924
5 0.02340090
6 0.95233233
这篇关于在purrr :: map_df之后如何使用映射向量添加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文