在 dplyr 分析中结合多个汇总统计

Combining multiple summary statistics in dplyr analysis

对于示例数据框:

df1 <- structure(list(practice = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), drug = c("123A456", 
"123A567", "123A123", "123A567", "123A456", "123A123", "123A567", 
"123A567", "998A125", "123A456", "998A125", "123A567", "123A456", 
"998A125", "123A567", "123A567", "123A567", "998A125", "123A123", 
"998A125", "123A123", "123A456", "998A125", "123A567", "998A125", 
"123A456", "123A123", "998A125", "123A567", "123A567", "998A125", 
"123A456", "123A123", "123A567", "123A567", "998A125", "123A456"
), items = c(1, 2, 3, 4, 5, 4, 6, 7, 8, 9, 5, 6, 7, 8, 9, 4, 
5, 6, 3, 2, 3, 4, 5, 6, 7, 4, 3, 2, 3, 4, 5, 4, 3, 4, 5, 6, 4
), quantity = c(1, 2, 4, 5, 3, 2, 3, 5, 4, 5, 7, 9, 5, 3, 4, 
6, 1, 2, 4, 5, 3, 2, 3, 5, 4, 5, 7, 9, 5, 3, 4, 6, 1, 2, 4, 5, 
3)), .Names = c("practice", "drug", "items", "quantity"), row.names = c(NA, 
-37L), spec = structure(list(cols = structure(list(practice = structure(list(), class = c("collector_integer", 
"collector")), drug = structure(list(), class = c("collector_character", 
"collector")), items = structure(list(), class = c("collector_integer", 
"collector")), quantity = structure(list(), class = c("collector_integer", 
"collector"))), .Names = c("practice", "drug", "items", "quantity"
)), default = structure(list(), class = c("collector_guess", 
"collector"))), .Names = c("cols", "default"), class = "col_spec"), class = c("tbl_df", 
"tbl", "data.frame"))

我想做各种分析。我认为 dplyr 将是我的解决方案,但我正在努力如何将功能组合在一起。

我的数据框是一个药物列表,我想总结其中一些药物(由药物代码的前三位数字定义)。

  1. 我想报告那些类型药物的总和(从 123 开始)- drug123.items 和 drug123.quantity BY practice.

  2. 我还想报告数据框中所有药物的所有药物(all_items 和 all_quantity)的总数(我最终将 drug123 表示为所有药物的百分比)。

我可以单独进行一些分析,例如通过以下方式总结总项目:

practice <- df1 %>% 
  group_by(practice) %>% 
  summarise(all.items = sum(items))

...而这只看我感兴趣的药物...

drug123 <- df1 %>% 
  filter(substr(drug, 1,3)==123)


ALL.drug123 <- aggregate(drug123$quantity, by=list(Category=drug123$practice), FUN=sum)

但是我该如何把所有东西放在一起呢?

我想要一个包含以下列的数据框:

练习(给定数据框中的 1,2,3)。

drug123.items #for drug123

drug123.quantity #for drug123

all.items #所有药物

all.quantity #所有药物

有什么想法吗?

我想这就是您要找的:

df1 %>%
  group_by(practice) %>%
  summarize(items_123 = sum(if_else(stringr::str_detect(drug, '^123'), items, 0)),
            quantity_123 = sum(if_else(stringr::str_detect(drug, '^123'), quantity, 0)),
            all_items = sum(items),
            all_quantity = sum(quantity))

# A tibble: 3 x 5
  practice items_123 quantity_123 all_items all_quantity
     <int>     <dbl>        <dbl>     <dbl>        <dbl>
1        1        54           44        75           58
2        2        44           42        66           65
3        3        24           19        35           28