How to add a column using the mapping vector after purrr::map_df

不想你离开。 提交于 2019-12-06 06:45:27

问题


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))))


回答1:


Using set_names should do it

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


来源:https://stackoverflow.com/questions/47189979/how-to-add-a-column-using-the-mapping-vector-after-purrrmap-df

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!