![](/img/trans.png)
[英]How to summarise by group AND get a summary of the overall dataset using dplyr in R
[英]How to use the summarise function to create a summary in R using dplyr package?
我有下表代表一個孩子,他的兄弟姐妹以及他們被分配的情況。 資源 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
任何幫助,將不勝感激。 我曾嘗試使用匯總功能,但這給了我單獨的每個案例 ID。
我推斷您的邏輯是“placed_together”中的“任何"Y"
,因為 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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.