R语言如何根据df1多列全0条件,删除df2中匹配的指定行
可复用过滤函数实现
函数代码
你可以直接使用以下自定义函数完成需求,依赖dplyr包实现:
library(dplyr) filter_df2 <- function(df1, df2, cols_df1, target_pattern) { # 校验输入的列长度是否符合要求 if(length(cols_df1) != 3) { stop("请输入长度为3的df1列名向量") } # 提取df1中三个指定列全为0的record_id remove_ids <- df1 %>% filter(if_all(all_of(cols_df1), ~ .x == 0)) %>% pull(record_id) # 过滤df2,删除符合条件的行 res_df2 <- df2 %>% filter(!(record_id %in% remove_ids & Pattern == target_pattern)) return(res_df2) }
使用示例
以你给出的测试场景为例,调用方式如下:
# 指定df1的3个列名和对应的Pattern取值 target_cols <- c("fracture_pattern___1", "fracture_pattern_radiology___1", "fracture_pattern_attending___1") target_patt <- "Lefort1" # 运行函数得到处理后的df2 processed_df2 <- filter_df2(df1, df2, target_cols, target_patt)
效果验证
原df2中共有2行符合record_id=51且Pattern=Lefort1的记录,运行函数后这2行会被删除,其余行全部保留,符合需求。
内容的提问来源于stack exchange,提问作者Joe Crozier
相关产品推荐
相关产品推荐

