【问题标题】:How to use the summarise function to create a summary in R using dplyr package?如何使用 summarise 函数在 R 中使用 dplyr 包创建摘要?
【发布时间】:2020-09-17 16:21:09
【问题描述】:

我有下表代表一个孩子,他的兄弟姐妹以及他们被分配的情况。资源 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_id 放在一起的孩子的总数和没有放在一起的孩子的总数。所以我的结果应该是这样的

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

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

【问题讨论】:

  • 能否请您提一下您如何根据输入计算汇总输出的逻辑

标签: r dplyr summarize


【解决方案1】:

我推断您的逻辑是“任何"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")

【讨论】:

    猜你喜欢
    • 2016-08-07
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 2020-01-21
    • 2015-04-27
    • 2018-07-12
    • 1970-01-01
    • 2019-03-04
    相关资源
    最近更新 更多