![](/img/trans.png)
[英]Calculate mean days in R using dplyr, filter, group_by and summarise?
[英](R, dplyr) select multiple columns starts with same string and summarise mean (90% CI) by group
我是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
另一個選項是summarise_at
。 vars(starts_with("ab"))
用於選擇列,funs 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
你非常接近,只需在summarise
之前移動select
。 然后我們使用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
調用需要更少的輸入,我們分別指定每個列和每個操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.