【问题标题】:subset rows in dataframe using combinations of conditions使用条件组合在数据框中子集行
【发布时间】:2021-07-23 03:07:02
【问题描述】:

我有一个数据框:

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)

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

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

【问题讨论】:

  • 注意:在 dplyr 函数中,您不需要 data$

标签: dplyr r filter dplyr subset


【解决方案1】:

我们可以使用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

或使用combnation 列

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

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

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

【讨论】:

  • 所需的输出应仅包括存在 Sp1 和 Sp3、存在 Sp1 和 Sp4 或存在 Sp3 和 Sp4 的图。因此,Plot 1、Plot 6 和 Plot 7 不应出现在结果数据框中。
  • @nateroe 此代码基于您在帖子table %&gt;% filter(table$Sp1 == 1 |table$Sp3 == 1 | table$Sp4 == 1)中的代码
  • 谢谢!这是完成那部分的更好方法。任何想法:但是,如果我想减少表格,以便只存在具有这些物种中的两个任意组合的地块,该怎么办。例如,Sp1 和 Sp3、Sp1 和 Sp4、Sp3 和 Sp4 的图将保留。
  • @nateroe 我猜你正在寻找成对操作,即nm1 &lt;- combn(c("Sp1", "Sp3", "Sp4"), 2, simplify = FALSE)
  • @nateroe 你想要更新中的输出吗
猜你喜欢
  • 2011-06-23
  • 2021-10-03
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多