r - 2组计数指标
问题描述
我有一个小组和每个小组的人。和一个指标。如何为每个人元素计算每个组的指标?
group person ind
1 1 1
1 1 1
1 2 1
2 1 0
2 2 1
2 2 1
输出所以在第一组中有 2 个人在 ind 中有 1 个,第二组有一个人所以
group person ind. count
1 1 1 2
1 1 1 2
1 2 1 2
2 1 0 1
2 2 1 1
2 2 1 1
解决方案
能做:
library(dplyr)
df %>%
group_by(group) %>%
mutate(
count = n_distinct(person[ind == 1])
)
输出:
# A tibble: 6 x 4
# Groups: group [2]
group person ind count
<int> <int> <int> <int>
1 1 1 1 2
2 1 1 1 2
3 1 2 1 2
4 2 1 0 1
5 2 2 1 1
6 2 2 1 1
或在data.table
:
library(data.table)
setDT(df)[, count := uniqueN(person[ind == 1]), by = group]