应用地图后保留列表名称

时间:2018-04-18 07:41:17

标签: r purrr

我将列表传递给map,并希望返回带有合并名称的data.frame对象。

例如:

library(tidyverse)
library(broom)

mtcars %>%
    split(.$vs) %>%
    map_df(~ tidy(lm(mpg ~ cyl, .)))

         term  estimate std.error statistic      p.value
1 (Intercept) 36.926733  3.690822 10.005017 2.727754e-08
2         cyl -2.728218  0.490297 -5.564419 4.272958e-05
3 (Intercept) 41.940000  5.778467  7.257981 1.003636e-05
4         cyl -3.802500  1.240052 -3.066404 9.781943e-03

如何在vs中提取名称(map组),并将其作为附加列添加到结果中,如下所示:

         term  estimate std.error statistic      p.value GROUP
1 (Intercept) 36.926733  3.690822 10.005017 2.727754e-08 0
2         cyl -2.728218  0.490297 -5.564419 4.272958e-05 0
3 (Intercept) 41.940000  5.778467  7.257981 1.003636e-05 1
4         cyl -3.802500  1.240052 -3.066404 9.781943e-03 1

2 个答案:

答案 0 :(得分:6)

使用.id参数,map_df将传递给dplyr::bind_rows

library(purrr)

mtcars %>%
    split(.$vs) %>%
    map_df(~broom::tidy(lm(mpg ~ cyl, .)), .id = 'GROUP')
#>   GROUP        term  estimate std.error statistic      p.value
#> 1     0 (Intercept) 36.926733  3.690822 10.005017 2.727754e-08
#> 2     0         cyl -2.728218  0.490297 -5.564419 4.272958e-05
#> 3     1 (Intercept) 41.940000  5.778467  7.257981 1.003636e-05
#> 4     1         cyl -3.802500  1.240052 -3.066404 9.781943e-03

答案 1 :(得分:2)

以下是group_by/nest/unnest

的一个选项
mtcars %>% 
  group_by(GROUP = vs) %>% 
  nest(-GROUP) %>%
  mutate(out = map(data, ~ tidy(lm(mpg ~ cyl, .x))) ) %>%
  select(-data) %>%
  unnest
# A tibble: 4 x 6
#   GROUP  term        estimate std.error statistic      p.value    
#   <dbl> <chr>          <dbl>     <dbl>     <dbl>        <dbl>
#1  0    (Intercept)    36.9      3.69      10.0  0.0000000273
#2  0    cyl           - 2.73     0.490    - 5.56 0.0000427   
#3  1.00 (Intercept)    41.9      5.78       7.26 0.0000100   
#4  1.00 cyl           - 3.80     1.24     - 3.07 0.00978