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

如何使用tidyverse筛选与指定id和condition匹配的数据框行?

在R语言中用tidyverse基于多列配对条件筛选数据框行

首先定义原始数据和筛选条件:

library(tidyverse)

df <- tibble(id = c(1, 1, 2, 2, 3, 3, 4, 5), 
             condition = c(1, 0, -1, 1, 0, 3, 2, 10), 
             distractor = c(10, 1, 10, 0.1, -5, 70, NA, 0.2))

selection <- tibble(id = c(1, 2, 3), condition = c(1, -1, 0))

方法1:使用inner_join()匹配多列

通过指定by参数为需要匹配的列(id和condition),inner_join()会返回两个数据框中这两列完全匹配的行:

result <- inner_join(df, selection, by = c("id", "condition"))
result

方法2:使用semi_join()筛选匹配行

semi_join()仅保留原始数据框中存在于筛选条件数据框里的行,不会额外添加列,更专注于筛选操作:

result <- semi_join(df, selection, by = c("id", "condition"))
result

预期输出

# A tibble: 3 × 3
     id condition distractor
  <dbl>     <dbl>      <dbl>
1     1         1       10  
2     2        -1       10  
3     3         0       -5  

内容的提问来源于stack exchange,提问作者medium-dimensional

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:40:30