(R,dplyr)选择多个列以相同的字符串开头,并按组汇总平均值(90%CI)

Lab*_*b.J 2 r dplyr tidyverse

我是tidyverse的新手,从概念上讲,我想计算平均值,所有列的90%CI以"ab"开头,按"case"分组.试过很多方法,但似乎没有工作,我的实际数据有很多列,所以明确列出它们不是一个选项.

测试数据如下

library(tidyverse)

dat <- tibble(case= c("case1", "case1", "case2", "case2", "case3"), 
              abc = c(1, 2, 3, 1, 2), 
              abe = c(1, 3, 2, 3, 4), 
              bca = c(1, 6, 3, 8, 9))
Run Code Online (Sandbox Code Playgroud)

下面的代码是我想在概念上做的,但显然不起作用

dat %>% group_by(`case`) %>% 
  summarise(mean=mean(select(starts_with("ab"))), 
            qt=quantile(select(starts_with("ab"), prob=c(0.05, 0.95))))
Run Code Online (Sandbox Code Playgroud)

我想得到的是下面的内容

case abc_mean abe_mean abc_lb abc_ub abe_lb abe_ub

  <chr>    <dbl>    <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
1 case1      1.5      2.0   1.05   1.95   1.10   2.90
2 case2      2.0      2.5   1.10   2.90   2.05   2.95
3 case3      2.0      4.0   2.00   2.00   4.00   4.00
Run Code Online (Sandbox Code Playgroud)

www*_*www 7

另一种选择是summarise_at.vars(starts_with("ab"))用于选择列,funs(...)是应用summarzing函数.

library(tidyverse)

dat2 <- dat %>% 
  group_by(case) %>% 
  summarise_at(vars(starts_with("ab")), funs(mean = mean(.),
                                             lb = quantile(., prob = 0.05),
                                             ub = quantile(., prob = 0.95))) 
dat2
# # A tibble: 3 x 7
#    case abc_mean abe_mean abc_lb abe_lb abc_ub abe_ub
#   <chr>    <dbl>    <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
# 1 case1      1.5      2.0   1.05   1.10   1.95   2.90
# 2 case2      2.0      2.5   1.10   2.05   2.90   2.95
# 3 case3      2.0      4.0   2.00   4.00   2.00   4.00
Run Code Online (Sandbox Code Playgroud)


bou*_*all 5

你非常接近,只是select在之前移动summarise.然后我们使用summarise_all,并在其中指定适当的函数funs.

dat %>%
    group_by(case) %>%
    select(starts_with('ab')) %>%
    summarise_all(funs('mean' = mean, 'ub' = quantile(., .95), 'lb' = quantile(., .05)))

# # A tibble: 3 x 7
#    case abc_mean abe_mean abc_ub abe_ub abc_lb abe_lb
#   <chr>    <dbl>    <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
# 1 case1      1.5      2.0   1.95   2.90   1.05   1.10
# 2 case2      2.0      2.5   2.90   2.95   1.10   2.05
# 3 case3      2.0      4.0   2.00   4.00   2.00   4.00
Run Code Online (Sandbox Code Playgroud)

我们使用summarise_all而不是summarise因为我们希望对多个列执行相同的操作.它使用的输入要少得多,summarise_all而不是summarise我们分别指定每列和每个操作的调用.