在嵌套的 tibble 上使用 select 时保留嵌套变量

标签 r dplyr tidyr purrr

我正在使用这个 question 中的代码(下)将嵌套的 tibble 列保存到新的 tibbles 列表中(每一列都是列表中的一个 tibble)。但是,在嵌套的 tibble 上使用 selected 时,嵌套的变量会丢失。我想保留的是,它使分组变量与结果保持一致。

例如,results %>% unnest(tidied) 保留“carb”,但 'results %>% 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(.))

最佳答案

我们可以在 select 步骤之前执行一个 mutate_at(虽然不清楚预期的输出)。这里的mutate_at在循环每一列,但是这些列也是tibble,所以在函数(list(~)里面,我们使用map2 传递列和 'carb' 列,然后通过 mutate 创建一个包含 list tibble 列的新列使用新列“carb”

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
#...
#...

关于在嵌套的 tibble 上使用 select 时保留嵌套变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56688634/

相关文章:

r - 合并弹性表的数据框

r - 为什么 "<<-"会扰乱 Shiny 中函数的范围

r - 从单独的列表创建嵌套的 data.frame

r - 如何改变R中数据框的形状? (将具有相同名称的列堆叠在一起)

r - 如何将不同列的数据整理成一个

r - 顺序向量或 POSIXct 不起作用

R:如何在 lapply() 中应用 grep()

r - 每周第二个星期二结束的 2 周总和

r - dplyr 版本的数据框分组然后在每组上创建回归模型

r - 将数据帧转换为 R 中一列的长格式