首页 > 解决方案 > 如何使用 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

这样每个具有特定编号的苹果都有一个匹配的具有相同编号的梨。

标签: rfilterdplyrstringr

解决方案


你可以这样做:

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    
> 

推荐阅读