按(排)对组合的过滤 [英] Filter by combination of (row) pairs
本文介绍了按(排)对组合的过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个长格式的数据帧,我想要基于唯一值组合的过滤对。我有一个如下所示的数据集:
id <- rep(1:4, each=2)
type <- c("blue", "blue", "red", "yellow", "blue", "red", "red", "yellow")
df <- data.frame(id,type)
df
id type
1 1 blue
2 1 blue
3 2 red
4 2 yellow
5 3 blue
6 3 red
7 4 red
8 4 yellow
假设每个id都是应答者,类型是治疗的组合。个人1看到两个物体,均为蓝色;个人2看到一个红色物体和一个黄色物体;以此类推。
例如,我如何保留那些看到"红色"和"黄色"组合的对象?如果我用过滤将"红色"和"黄色"组合起来,结果数据集应该如下所示: id type
3 2 red
4 2 yellow
7 4 red
8 4 yellow
它应该保持2号和4号受访者(仅限于看到"红色"和"黄色"组合的受访者)。请注意,它没有保留3号答复者,因为她看到的是"蓝色"和"红色"(而不是"红色"和"黄色")。我该怎么做?
一种解决方案是将数据集重塑为宽格式,逐列对其进行过滤,然后再次重新堆叠。但我相信有另一种方法可以做到这一点,而不需要重塑数据集。有什么想法吗?推荐答案
Adplyr
解决方案为:
library(dplyr)
df <- data_frame(
id = rep(1:4, each = 2),
type = c("blue", "blue", "red", "yellow", "blue", "red", "red", "yellow")
)
types <- c("red", "yellow")
df %>%
group_by(id) %>%
filter(all(types %in% type))
#> # A tibble: 4 x 2
#> # Groups: id [2]
#> id type
#> <int> <chr>
#> 1 2 red
#> 2 2 yellow
#> 3 4 red
#> 4 4 yellow
更新
考虑到相等的组合,例如blue
,blue
,我们必须将过滤调用更改为:
types2 <- c("blue", "blue")
df %>%
group_by(id) %>%
filter(sum(types2 == type) == length(types2))
#> # A tibble: 2 x 2
#> # Groups: id [1]
#> id type
#> <int> <chr>
#> 1 1 blue
#> 2 1 blue
此解决方案还允许不同的类型
df %>%
group_by(id) %>%
filter(sum(types == type) == length(types))
#> # A tibble: 4 x 2
#> # Groups: id [2]
#> id type
#> <int> <chr>
#> 1 2 red
#> 2 2 yellow
#> 3 4 red
#> 4 4 yellow
这篇关于按(排)对组合的过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文