【问题标题】:How to add a column using the mapping vector after purrr::map_df如何在 purrr::map_df 之后使用映射向量添加列
【发布时间】:2017-11-08 21:28:33
【问题描述】:

我以 mtcars 数据集为例来说明我的问题。我对每种气缸类型进行了线性回归,并使用 map_df 将所有模型结果放在一起。 (下面的代码和输出)。我想要做的是添加另一列名为“圆柱体”(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))))

【问题讨论】:

  • 您是否愿意接受循环字符向量的替代方法?我可能会将 split 数据集放入圆柱组中,在这种情况下 .id 会起作用:split(mtcars, mtcars$cyl) %&gt;% map_df(~tidy(lm(hp ~ wt, data = .)), .id = "cylinder")
  • 您还可以设置cyls 的名称以在您当前的工作流程中使用map_df 中的.idcyls = set_names(cyls)
  • @aosmith 谢谢。我不接受替代品。我知道该怎么做。但我需要弄清楚如何在我的实际工作中使用 map_df。
  • @aosmith 是的。那可行。非常感谢!

标签: r dplyr purrr


【解决方案1】:

使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-19
    • 2022-01-13
    • 2021-10-09
    • 2018-07-03
    • 1970-01-01
    • 2018-10-22
    • 2012-09-24
    相关资源
    最近更新 更多