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

如何筛选R数据框中每个id对应name同时含pre和after标签的行

解决方法:筛选每个id下同时包含pre/after label的name行

嘿,这个需求用dplyr包就能轻松实现,咱们一步步来:

首先,先确认我们的原始数据框:

dframe <- structure(list(id = c(1L, 1L, 1L, 1L), name = c("Amazon", "Google", "Google", "Yahoo"), label = c("pre", "after", "pre", "after"), text_sth = c("other", "another one test text_sth another text", "another text other", "another one test text_sth another text" )), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -4L))

接下来,我们需要按id和name分组,然后检查每个组里是否同时存在pre和after两种label,最后保留符合条件的组的所有行:

# 先加载dplyr(没安装的话先跑install.packages("dplyr"))
library(dplyr)

filtered_dframe <- dframe %>%
  # 按用户id和名称分组
  group_by(id, name) %>%
  # 筛选出组内同时包含pre和after的行
  filter(all(c("pre", "after") %in% label)) %>%
  # 取消分组,恢复普通数据框结构
  ungroup()

# 查看结果
filtered_dframe

代码解释:

  • group_by(id, name):把数据拆分成"每个用户id下的每个name"这样的小组,确保我们能针对每个小组单独检查label条件
  • filter(all(c("pre", "after") %in% label)):c("pre", "after") %in% label会检查这两个值是否存在于当前组的label列中,all()函数确保两个值都必须存在,只有满足这个条件的小组才会被保留
  • ungroup():取消分组,让结果回到标准的tbl_df格式,方便后续操作

运行这段代码后,你会得到预期的输出:

# A tibble: 2 × 4
     id name   label text_sth                                    
  <int> <chr>  <chr> <chr>                                       
1     1 Google after another one test text_sth another text
2     1 Google pre   another text other

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:05:28