r - 如何使用 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 的总数。
解决方案
我推断您的逻辑是"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")
推荐阅读
- python - 在 RDFLIB 和 Python 中为 Sparql 更新语句使用具有存储值的变量
- javascript - js中的动态多维数组
- reactjs - 从 React 应用程序中提取组件 Html Css Js
- reactjs - React Router 移除服务器前缀(反向代理)
- c++ - pybind11 与 CMakeLists 仅用于标头库?
- nearprotocol - 无法通过 Sputnik v2 上的自定义函数调用表单“stake_and_deposit”超过 24 N
- javascript - fabric.js 生成与我的画布大小相同的图像
- flutter - 如何在 Navigator.push 之后从父屏幕显示小部件而不重建
- python - pandas:从给定日期开始按月分组
- javascript - 如何为某些路由添加自定义类到 body 元素 - nexjts