gpt4 book ai didi

r - 通过使用涉及两列的两个单独的选择标准使用 dplyr 进行过滤

转载 作者:行者123 更新时间:2023-12-04 15:58:17 26 4
gpt4 key购买 nike

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

我下面的 reprex 模拟了一个包含 4 个样本的 data.frame:ControlDrug_1Drug_2、和 Drug_3 以及它们之间的成对比较(差异显示为 p_value)。我想在一个函数中使用这段代码来比较 4 个以上的组。我尝试将过滤条件与 OR 运算符结合使用,但我以一个相当难看的代码结束。

我的最终目标是获得一个 filtered_df,它显示变量 group1group2 具有我的数据对的所有行比较 列表。感谢您的帮助!

最好的,阿塔坎

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 创建于 2018-06-29 (v0.2.0).

最佳答案

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

1) 一种方法是遍历 list('comparisons'),然后对数据集个体进行 filter 并绑定(bind)一起输出 (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"))

关于r - 通过使用涉及两列的两个单独的选择标准使用 dplyr 进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51111157/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com