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

时间:2017-11-14 19:19:19

标签: 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))

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

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

我想得到的是下面的内容

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

2 个答案:

答案 0 :(得分: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

我们使用summarise_all代替summarise,因为我们希望在多个列上执行相同的操作。使用summarise_all代替summarise调用所需的输入要少得多,我们会分别指定每个列和每个操作。

答案 1 :(得分:5)

另一个选项是public void kuehlschrankInformationen(){ dimensionen = "Die Breite beträgt 178cm, die Höhe 66,8cm & die Länge 59,5cm"; verbrauch = 157; volumen = 707.5; // in liter name = "Build Your Body Fat"; gewicht = 63; try{ System.out.println(name); System.out.println(gewicht); System.out.println(volumen +" Liter"); System.out.println("Der Kühlschrank verbraucht " + verbrauch + "kWh"); System.out.println(dimensionen); TimeUnit.SECONDS.sleep(5); summarise_at用于选择列,vars(starts_with("ab"))用于应用summarzing函数。

funs(...)
相关问题