首页 > 解决方案 > 如何使用 summarise 函数在 R 中使用 dplyr 包创建摘要?

问题描述

我有下表代表一个孩子,他的兄弟姐妹以及他们被分配的情况。资源 id 代表它们被放在一起的房子。

child_id|sibling_id|case_id|resource_id|placed_together
    1       8         123      12856     Y
    1       9         123      12856     Y
    3      11         321      12555     N
    4      12         323      10987     N
    4      13         323      10956     N
    6      14         156      10554     N
    6      15         156      10554     N
   10      16         156      10553     N
   10      17         145      18986     Y
   10      18         145      18986     Y

我想创建一个摘要,显示根据他们的 case_ids 放在一起的孩子的总数和那些没有放在一起的孩子的总数。所以我的结果应该是这样的

Total Groups|sibling placed together|siblings not placed together
        5             2                   3      
   

任何帮助,将不胜感激。我曾尝试使用 summarise 函数,但它分别为我提供了每个案例 ID 的总数。

标签: rdplyrsummarize

解决方案


我推断您的逻辑是"any "Y"in `placed_together",因为 id 10 有一个“N”和两个“Y”用于兄弟位置。

library(dplyr)
dat %>%
  group_by(child_id) %>%
  summarize(tog = "Y" %in% unique(placed_together)) %>%
  ungroup() %>%
  summarize(TotalGroups = n(), Together = sum(tog), NotTogether = sum(!tog))
# # A tibble: 1 x 3
#   TotalGroups Together NotTogether
#         <int>    <int>       <int>
# 1           5        2           3

数据

dat <- read.table(header=T, text="
child_id sibling_id case_id resource_id placed_together
    1       8         123      12856     Y
    1       9         123      12856     Y
    3      11         321      12555     N
    4      12         323      10987     N
    4      13         323      10956     N
    6      14         156      10554     N
    6      15         156      10554     N
   10      16         156      10553     N
   10      17         145      18986     Y
   10      18         145      18986     Y")

推荐阅读