【问题标题】:Filtering with dplyr by using two separate selection criteria involving two columns通过使用涉及两列的两个单独的选择条件使用 dplyr 进行过滤
【发布时间】:2018-12-09 04:55:09
【问题描述】:

我正在尝试有条件地过滤数据框以提取感兴趣的行。我正在尝试做的与通用条件过滤不同,因为它涉及影响列对的可变规则。

我下面的代表模拟了一个data.frame,它涉及4个样本:ControlDrug_1Drug_2Drug_3,并在它们之间进行成对比较(差异显示为p_value)。我想在一个函数中使用这段代码来潜在地比较超过 4 个组。我尝试将过滤条件与OR 运算符结合起来,但我以一个相当难看的代码结束。

我的最终目标是获得一个filtered_df,它显示变量group1group2 具有我的comparisons 列表中的数据对的所有行。任何帮助表示赞赏!

最好, 阿塔坎

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

# Make a mock data frame
gene <- "ABCD1"
group1 <- c("Control", "Control", "Control", "Drug_1", "Drug_1", "Drug_2")
group2 <- c("Drug_1", "Drug_2", "Drug_3", "Drug_2", "Drug_3", "Drug_3")
p_value <- c(0.4, 0.001, 0.003, 0.01, 0.3, 0.9)

df <- data.frame(gene, group1, group2, p_value)
df
#>    gene  group1 group2 p_value
#> 1 ABCD1 Control Drug_1   0.400
#> 2 ABCD1 Control Drug_2   0.001
#> 3 ABCD1 Control Drug_3   0.003
#> 4 ABCD1  Drug_1 Drug_2   0.010
#> 5 ABCD1  Drug_1 Drug_3   0.300
#> 6 ABCD1  Drug_2 Drug_3   0.900

# I'd like to filter rows when group1 and group2 matches the following pairs
comparisons <- list(c("Control", "Drug_1"), c("Control", "Drug_2"), c("Drug_2", "Drug_3"))


# I can filter by using one pair as follows:
filtered_df <- df %>%
  filter(group1 == comparisons[[1]][1] & group2 == comparisons[[1]][2])

filtered_df
#>    gene  group1 group2 p_value
#> 1 ABCD1 Control Drug_1     0.4

reprex package (v0.2.0) 于 2018 年 6 月 29 日创建。

【问题讨论】:

  • 你需要map_df(comparisons, ~ df %&gt;% filter(group1 == .x[1] &amp; group2 == .x[2]))
  • 或者将列表转换为data.frame后使用inner_join do.call(rbind, comparisons) %&gt;% as.data.frame %&gt;% set_names(c("group1", "group2")) %&gt;% inner_join(df)
  • @akrun: map_df 有效。你能解释一下你的答案吗?

标签: r dplyr filtering multiple-conditions


【解决方案1】:

我们可以通过几种方式做到这一点。

1) 一种方法是循环遍历list('comparisons'),然后对数据集个体执行filter 并将输出绑定在一起(map_df

library(tidyverse)
map_df(comparisons, ~ df %>%
                         filter(group1 == .x[1] & group2 == .x[2]))

2) 另一种选择是将list 转换为data.frame 并使用第一个数据集执行inner_join

do.call(rbind, comparisons) %>% # rbind to a matrix
         as.data.frame %>% # convert to a data.frame
         set_names(c("group1", "group2")) %>% # change the column names
         inner_join(df) # and inner join

3)或使用base R中的merge(类似于2)

merge(df, as.data.frame(do.call(rbind, comparisons)),
            by.x = c("group1", "group2"), by.y = c("V1", "V2"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    相关资源
    最近更新 更多