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