使用条件组合在数据框中子集行

subset rows in dataframe using combinations of conditions

我有一个数据框:

table = structure(list(Plot = 1:10, Sp1 = c(0L, 0L, 1L, 1L, 0L, 1L, 0L, 
                                    0L, 1L, 0L), Sp2 = c(1L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L), 
               Sp3 = c(1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 0L, 0L), Sp4 = c(0L, 
                                                                        1L, 1L, 0L, 1L, 0L, 0L, 1L, 1L, 0L)), class = "data.frame", row.names = c(NA, 
                                                                                                                                                  -10L))

0 表示地块中不存在物种 (Sp)。 1代表一个物种存在。

首先,我想对我的数据框进行子集化,以便只保留带有 Sp1 或 Sp3 或 Sp4 的图。这可以通过 :

中的 filter 轻松完成
reduced_table <- table %>% filter(table$Sp1 == 1 |table$Sp3 == 1 | table$Sp4 == 1)

但是,如果我想减少 table 以便只存在具有这两个物种的任意组合的地块,该怎么办。例如,带有 Sp1 和 Sp3,或 Sp1 和 Sp4,或 Sp3 和 Sp4 的地块将保留。

这能像使用 filter 一样雄辩地完成吗?我的真实情况有更多的物种,因此有更多的组合,所以明确地写出这些组合并不理想。

我们可以使用 if_anyfilter

library(dplyr)
table %>%
   filter(if_any(c(Sp1, Sp3, Sp4), ~ .== 1))

-输出

#   Plot Sp1 Sp2 Sp3 Sp4
#1    1   0   1   1   0
#2    2   0   0   1   1
#3    3   1   1   1   1
#4    4   1   0   1   0
#5    5   0   0   1   1
#6    6   1   0   0   0
#7    7   0   1   1   0
#8    8   0   0   1   1
#9    9   1   0   0   1

或使用combn

library(purrr)
combn(c("Sp1", "Sp3", "Sp4"), 2, simplify = FALSE) %>%
  map_dfr( ~ table %>%
         filter(if_all(.x, ~ . == 1))) %>%
  distinct

如果打算对成对列检查进行过滤,请使用 base R

中的 combn
subset(table, Reduce(`|`, combn(c("Sp1", "Sp3", "Sp4"), 2, 
  FUN = function(x) rowSums(table[x] == 1) == 2, simplify = FALSE)))