r - 如何使用 R 中的 filter 和 str_detect 过滤具有部分匹配对的数据?
问题描述
我正在尝试过滤具有匹配组的数据,如果它们没有匹配组,我想删除这些观察结果。
例如,如果我有一个数据集:
# condition group type
#1 apple_1 B small
#2 apple_1 A small
#3 apple 1 A small
#4 apple_2 A small
#5 apple_2 A small
#6 apple_3 A small
#7 pear_1 A small
#8 pear_1 A small
#9 pear_1 A small
#10 pear_2 A small
#11 pear_3 A small
在这里,我决定每个苹果观察必须通过它们的数量与每对观察配对(例如,apple_3 应该与 pear_3 配对)。因此我们可以看到,由于只有一个 pear_2 观察值,因此应删除 apple_2 观察值之一,因为有两个 apple_2 观察值。此外,由于第一个 apple_1 在组 B 中,因此不匹配任何梨,因此应删除组 B 的 apple_1,并且应删除 pear_1 观察,因为它没有匹配对。
这里的问题是观察是使用下划线命名的,所以我需要以某种方式操作str_detect
并且组需要匹配,所以我也需要使用filter
。我觉得这种类型的过滤可以使用 来完成dplyr
,但我不确定。
预期结果应该是:我正在寻找的预期结果是这样的:
# condition group type
#1 apple_1 A small
#2 apple_1 A small
#3 apple_2 A small
#4 apple_3 A small
#5 pear_1 A small
#6 pear_1 A small
#7 pear_2 A small
#8 pear_3 A small
这样每个具有特定编号的苹果都有一个匹配的具有相同编号的梨。
解决方案
你可以这样做:
vec_drop <- function(x){
b <- table(x)
if(length(b)<2) return(FALSE)
a <- split(!logical(length(x)), x)
if (length(unique(b))>1)
a[[names(which.max(b))]][seq(abs(diff(b)))] <- FALSE
unsplit(a, x)
}
df %>%
group_by(group, cond = str_remove(condition, "\\w+_"))%>%
filter(vec_drop(condition))
condition group type cond
<chr> <chr> <chr> <chr>
1 apple_1 A small 1
2 apple_1 A small 1
3 apple_2 A small 2
4 apple_3 A small 3
5 pear_1 A small 1
6 pear_1 A small 1
7 pear_2 A small 2
8 pear_3 A small 3
>
推荐阅读
- neutrinos-platform - 如何使用 Neutrinos 平台创建一个简单的登录页面/
- r - 我想根据产品列在 R 中编写串联代码
- node.js - 在 npm (laravel) 中编译 webpack 时出错
- android - 如何更改 xamarin.android 中默认显示警报的背景颜色?
- java - 无法在测试注释方法中传递驱动程序值
- python-3.x - 如何在 matplotlib ax.imshow() 中使用“extent”而不更改覆盖的 ax.text() 句柄的位置?
- python - 更改重复值索引
- actionscript-3 - 这是我的 AS3 AIR 桌面应用程序中的内存泄漏,还是我不应该担心?
- neo4j - Neo4j:启动 Neo4j 太慢并且失败
- python - 有没有办法逐步计算列的数据框的平均值?