Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在purrr::map_df之后使用映射向量添加列_R_Dplyr_Purrr - Fatal编程技术网

如何在purrr::map_df之后使用映射向量添加列

如何在purrr::map_df之后使用映射向量添加列,r,dplyr,purrr,R,Dplyr,Purrr,我以mtcars数据集为例来说明我的问题。我对每种圆柱体类型进行线性回归,并使用map_df将所有模型结果放在一起。(下面是代码和输出)。我想做的是添加另一个名为“圆柱体”(4,4,6,6,8,8)的列。我如何在map_df中做到这一点?当我添加argument.id='cylinder'时,我只得到一列1,1,2,2,3,3。先谢谢你 library(purrr) cyls <- c(4,6,8) map_df(cyls, ~tidy(lm(hp~wt,data=mtcars %>

我以mtcars数据集为例来说明我的问题。我对每种圆柱体类型进行线性回归,并使用map_df将所有模型结果放在一起。(下面是代码和输出)。我想做的是添加另一个名为“圆柱体”(4,4,6,6,8,8)的列。我如何在map_df中做到这一点?当我添加argument.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))))
库(purrr)
气缸%过滤器(气缸==.x)))

使用
设置名称应该可以做到这一点

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

您是否愿意接受通过字符向量循环的替代方案?我可能会
将数据集拆分为圆柱体组,在这种情况下,
.id
会起作用:
拆分(mtcars,mtcars$cyl)%>%map\u df(~tidy(lm(hp~wt,data=),.id=“cyland”)
您还可以设置要使用的
cyl的名称。
id
在当前工作流程中的
map\u df
中:
cyls=set\u name(cyls)
@aosmith谢谢。我不愿意接受其他选择。我知道如何这样做。但我需要弄清楚在我的实际工作中如何使用map_df来做到这一点。@aosmith是的。那就行了。谢谢!