You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用dplyr的filter()筛选3列中至少一列值为D的dataframe行?

使用dplyr筛选指定列中至少有一个值为"D"的行

首先构造你提供的示例数据框:

library(dplyr)

df <- tibble(
  identifier = c(1, 2, 3, 4),
  def = c("D", "A", "B", "A"),
  abc = c("C", "D", "C", "D"),
  ghi = c("A", "D", "A", "A")
)

方法1:直接用逻辑或(|)连接条件

适合列数较少的场景,直接把每个目标列的判断用|连接:

filtered_df <- df %>%
  filter(def == "D" | abc == "D" | ghi == "D")

方法2:使用if_any()函数(推荐)

如果目标列较多,用if_any()更简洁(需要dplyr 1.0.0及以上版本),它会检查指定列中是否至少有一列满足条件:

# 定义目标列向量
target_cols <- c("def", "abc", "ghi")

filtered_df <- df %>%
  filter(if_any(all_of(target_cols), ~ .x == "D"))

筛选结果

运行上述代码后,得到的filtered_df就是你需要的结果:

print(filtered_df)
# # A tibble: 3 × 4
#   identifier def   abc   ghi  
#        <dbl> <chr> <chr> <chr>
# 1          1 D     C     A    
# 2          2 A     D     D    
# 3          4 A     D     A    

内容的提问来源于stack exchange,提问作者Donut

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 02:40:41