我们可以使用n_distinct在filter中按'study'分组后创建条件
library(dplyr)
h %>%
group_by(study) %>%
filter(n_distinct(group) == 1, n_distinct(outcome) > 1)
# A tibble: 2 x 3
# Groups: study [1]
study outcome group
<chr> <int> <int>
1 a 1 1
2 a 2 1
或使用base R
subset(h, ave(group, study, FUN = function(x) length(unique(x)))
== 1 & ave(outcome, study, FUN = function(x) length(unique(x)) > 1))
study outcome group
1 a 1 1
2 a 2 1
如果我们愿意,我们可以概括
f1 <- function(dat, cond) {
switch(cond,
`1` = dat %>%
group_by(study) %>%
filter(n_distinct(group) == 1, n_distinct(outcome) > 1) %>%
ungroup,
`2` = dat %>%
group_by(study) %>%
filter(n_distinct(group) > 1, n_distinct(outcome) == 1) %>%
ungroup,
`3` = dat %>%
group_by(study) %>%
filter(n_distinct(group) > 1, n_distinct(outcome) > 1) %>%
ungroup,
`4` = dat %>%
group_by(study) %>%
filter(n_distinct(group) == 1, n_distinct(outcome) == 1) %>%
ungroup
)
}
-测试
> f1(h, 1)
# A tibble: 2 x 3
study outcome group
<chr> <int> <int>
1 a 1 1
2 a 2 1
> f1(h, 2)
# A tibble: 2 x 3
study outcome group
<chr> <int> <int>
1 b 1 1
2 b 1 2
> f1(h, 3)
# A tibble: 2 x 3
study outcome group
<chr> <int> <int>
1 c 2 1
2 c 3 2
> f1(h, 4)
# A tibble: 3 x 3
study outcome group
<chr> <int> <int>
1 d 1 1
2 d 1 1
3 e 1 1