首页 > 解决方案 > Map mean_se group_by 组合无法处理因子 group_by

问题描述

我想使用mean_seggplot 中的函数获得分组均值和相应的 se,但添加 group_by 会破坏该函数。我不得不求助于旋转和更长的汇总/变异管道,但想弄清楚如何在没有预先进行所有数据操作的情况下一次性完成。我的数据集有 14 个感兴趣的列 + 1 个 group_by,但我将使用所有 iris(因此跳过select()管道)以实现可重复性。将第一个(不起作用,但这是我想要的)与其余的进行比较:

iris %>% group_by(Species) %>% #Error
  map(~(mean_se(.)))

iris %>% select(-Species) %>% 
  map(~(mean_se(.))) #global mean+se


iris %>% select(-Species) %>% 
  map_dfr(~(mean_se(.)), id = "Species") %>% broom::tidy() #Gives 3 but which is which and how so if Species is unselected?

iris %>%
  map_dfr(~(mean_se(.))) %>% broom::tidy() #Error 

iris %>%
  map_dfr(~(mean_se(.)), id = "Species") %>% broom::tidy() #Also error

iris %>%  #Runs but the 
  group_by(Species) %>% #output doesn't make sense, 
  group_modify(~  #there should only be 3 columns (y, ymin, ymax) not 13
    .x %>%
      map_dfc(mean_se))

map_dfr 不尊重.id命令,如果必须删除分组变量以避免Error in stats::var(x) : Calling var(x) on a factor x is defunct. Use something like 'all(duplicated(x)[-1L])' to test for a constant vector.

标签: rggplot2dplyr

解决方案


或者:

iris %>% 
   group_by(Species) %>%
   summarise(across(everything(), mean_se))

# A tibble: 3 x 5
  Species    Sepal.Length$y $ymin $ymax Sepal.Width$y $ymin $ymax Petal.Length$y $ymin $ymax Petal.Width$y $ymin $ymax
  <fct>               <dbl> <dbl> <dbl>         <dbl> <dbl> <dbl>          <dbl> <dbl> <dbl>         <dbl> <dbl> <dbl>
1 setosa               5.01  4.96  5.06          3.43  3.37  3.48           1.46  1.44  1.49         0.246 0.231 0.261
2 versicolor           5.94  5.86  6.01          2.77  2.73  2.81           4.26  4.19  4.33         1.33  1.30  1.35 
3 virginica            6.59  6.50  6.68          2.97  2.93  3.02           5.55  5.47  5.63         2.03  1.99  2.06 

或者如果你想要更长的形式:

iris %>% 
   group_by(Species) %>%
   summarise(across(everything(), mean_se)) %>%
   pivot_longer(-Species)


# A tibble: 12 x 3
   Species    name         value$y $ymin $ymax
   <fct>      <chr>          <dbl> <dbl> <dbl>
 1 setosa     Sepal.Length   5.01  4.96  5.06 
 2 setosa     Sepal.Width    3.43  3.37  3.48 
 3 setosa     Petal.Length   1.46  1.44  1.49 
 4 setosa     Petal.Width    0.246 0.231 0.261
 5 versicolor Sepal.Length   5.94  5.86  6.01 
 6 versicolor Sepal.Width    2.77  2.73  2.81 
 7 versicolor Petal.Length   4.26  4.19  4.33 
 8 versicolor Petal.Width    1.33  1.30  1.35 
 9 virginica  Sepal.Length   6.59  6.50  6.68 
10 virginica  Sepal.Width    2.97  2.93  3.02 
11 virginica  Petal.Length   5.55  5.47  5.63 
12 virginica  Petal.Width    2.03  1.99  2.06 

推荐阅读