在嵌套的小对象上使用选择时保留嵌套变量

时间:2019-06-20 14:51:43

标签: r dplyr tidyr purrr

我正在使用此question(如下)中的代码将嵌套的小标题列保存到新的小标题列表中(每列是列表中的小标题)。但是,在嵌套的小对象上使用select时,嵌套的变量会丢失。我想保留它,它将分组变量与结果保持在一起。

例如,results %>% unnest(tidied)保留“ carb”,但“结果%>%select(tidied)%>%map(〜bind_rows(。))”不是。

如何将嵌套变量保留在选定的列中?

library(tidyverse)
library(broom)
data(mtcars)
df <- mtcars

nest.df <- df %>% nest(-carb) 

results <- nest.df %>% 
  mutate(fit = map(data, ~ lm(mpg ~ wt, data=.x)),
         tidied = map(fit, tidy),
         glanced = map(fit, glance),
         augmented = map(fit, augment))

final <- results %>% select(glanced, tidied, augmented ) %>% 
        map(~bind_rows(.))

1 个答案:

答案 0 :(得分:1)

我们可以在mutate_at步骤之前做一个select(尽管不清楚预期的输出)。这里的mutate_at遍历了每一列,但是这些列也是tibble,因此在函数(list(~)中,我们使用map2来传递列和'carb '列,然后通过list添加新列'carb'来创建tibble mutate列的新列

results %>%
  mutate_at(vars(glanced, tidied, augmented), 
          list(~ map2(.,carb, ~ .x %>% mutate(carb = .y)))) %>% 
  select(glanced, tidied, augmented) %>% 
  map(~ bind_rows(.x))
$glanced
# A tibble: 6 x 12
#  r.squared adj.r.squared  sigma statistic   p.value    df logLik    AIC    BIC deviance df.residual  carb
#      <dbl>         <dbl>  <dbl>     <dbl>     <dbl> <int>  <dbl>  <dbl>  <dbl>    <dbl>       <int> <dbl>
#1   0.696           0.658   2.29  18.3      0.00270      2 -21.4    48.7   49.6    41.9            8     4
#2   0.654           0.585   3.87   9.44     0.0277       2 -18.2    42.4   42.3    74.8            5     1
#3   0.802           0.777   2.59  32.3      0.000462     2 -22.6    51.1   52.1    53.5            8     2
#4   0.00295        -0.994   1.49   0.00296  0.965        2  -3.80   13.6   10.9     2.21           1     3
#5   0               0     NaN     NA       NA            1 Inf    -Inf   -Inf       0              0     6
#6   0               0     NaN     NA       NA            1 Inf    -Inf   -Inf       0              0     8

#$tidied
# A tibble: 10 x 6
#   term        estimate std.error statistic      p.value  carb
#   <chr>          <dbl>     <dbl>     <dbl>        <dbl> <dbl>
# 1 (Intercept)   27.9       2.91     9.56     0.0000118      4
# 2 wt            -3.10      0.724   -4.28     0.00270        4
#...
#...