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

在数据框不同列中查找匹配行的函数实现需求

如何在R数据框的列间查找匹配行并添加结果列

没问题,这事儿用R的基础函数就能轻松搞定!我给你一步步来:

首先先把你的示例数据框建出来,建议加上stringsAsFactors = FALSE避免默认的因子类型坑:

df <- data.frame(
  id=c("good","bad","ugly","dirty","clean","frenzy"),
  di=c(1,2,"good","dirty",4,"ugly"),
  stringsAsFactors = FALSE
)

接下来就是核心操作——用%in%判断di列的每个值是否存在于id列,再通过ifelse转换成你要的文本标签,直接新增match列:

df$match <- ifelse(df$di %in% df$id, "has matches", "no matches")

运行完之后,查看结果:

print(df)

输出结果:

id    di        match
1   good     1 no matches
2    bad     2 no matches
3   ugly  good has matches
4  dirty dirty has matches
5  clean     4 no matches
6 frenzy  ugly has matches

小补充(可选)

如果你的实际数据里可能存在NA值,想要把NA也统一标记为"no matches"的话,调整一下代码就行:

df$match <- ifelse(!is.na(df$di) & df$di %in% df$id, "has matches", "no matches")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:15:19