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

标签 r dplyr tidyverse

我是 tidyverse 的新手,从概念上讲,我想计算所有列的均值和 90% CI 以“ab”开头,按“案例”分组。尝试了很多方法,但似乎都不起作用,我的实际数据有很多列,因此明确列出它们不是一种选择。

测试数据如下

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

最佳答案

另一个选项是summarise_atvars(starts_with("ab")) 用于选择列,funs(...) 用于应用汇总函数。

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

关于r - (R, dplyr) 选择多个以相同字符串开头的列并按组汇总平均值 (90% CI),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47293652/

相关文章:

R - 排序后检索行号

r - 在 df2 的日期时间中使用 df1 的 "hour"和 "min"上的条件合并 2 个数据帧

r - 错误: 'across' is not an exported object from 'namespace:collapse'

r - 我的 aggregate() 输出和 tidyverse 输出之间的区别

r - 使用 `glue` 将一列中的变量替换为另一列中的变量

r - Purrr 映射到拆分的数据帧上以获得每个组的 AUROC

r - 根据 Shiny 仪表板中选择的选项卡面板隐藏和显示侧边栏

r - 如何为graphNEL图的节点着色?

r - 更改堆叠条形图的绘制顺序

r - 使用每个输入变量的多个输出变量跨 case_when 进行变异