应用地图后保留列表名称

问题描述 投票:5回答:2

我正在将列表传递到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
r purrr
2个回答
7
投票

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

library(purrr)

mtcars %>%
    split(.$vs) %>%
    map_dfr(~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

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     
© www.soinside.com 2019 - 2024. All rights reserved.