如何在 purrr::map_df 之后使用映射向量添加列
How to add a column using the mapping vector after purrr::map_df
我以 mtcars 数据集为例来说明我的问题。我 运行 对每个气缸类型进行线性回归,并使用 map_df 将所有模型结果放在一起。 (下面的代码和输出)。我想要做的是添加另一个名为 'cylinder' (4,4,6,6,8,8) 的列。我怎样才能在 map_df 中做到这一点?当我添加参数 .id='cylinder' 时,我只得到一列 1,1,2,2,3,3。非常感谢。
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
我以 mtcars 数据集为例来说明我的问题。我 运行 对每个气缸类型进行线性回归,并使用 map_df 将所有模型结果放在一起。 (下面的代码和输出)。我想要做的是添加另一个名为 'cylinder' (4,4,6,6,8,8) 的列。我怎样才能在 map_df 中做到这一点?当我添加参数 .id='cylinder' 时,我只得到一列 1,1,2,2,3,3。非常感谢。
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