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

如何判断一列文本字符串是否存在于另一列?附R语言示例

如何判断一列文本字符串是否存在于另一列并生成目标结果?

需求说明

给定两组文本向量df1和df2,需先判断df1中的每个字符串是否存在于df2的任意字符串中,最终生成包含df2全部内容,以及df1中未在df2里匹配到的内容的结果df3。

示例数据

df1 <- c("Board of Accountancy", "Board of Economists", "Board of Medicine")
df2 <- c("State Board of Accountancy", "The State Board of Economists", "State Board of Law")

步骤1:判断df1字符串是否存在于df2中

使用基础R的sapply结合grepl、any函数,可快速判断df1每个元素是否在df2中出现:

# 生成逻辑向量,标记df1每个元素是否在df2中有匹配
df1_match_status <- sapply(df1, function(x) any(grepl(x, df2)))

# 查看结果
df1_match_status
# 输出:
# Board of Accountancy    Board of Economists      Board of Medicine 
#                TRUE                 TRUE                FALSE 
  • grepl(x, df2):检查df2的每个元素是否包含字符串x,返回对应逻辑值
  • any():判断该逻辑向量中是否存在至少一个TRUE,即x是否在df2的任意元素中出现

步骤2:生成目标结果df3

提取df1中未匹配的元素,与df2合并即可得到df3:

# 提取df1中未匹配的元素
df1_unmatched <- df1[!df1_match_status]

# 合并df2和未匹配的df1元素
df3 <- c(df2, df1_unmatched)

# 查看最终结果
df3
# 输出:
# [1] "State Board of Accountancy"    "The State Board of Economists"
# [3] "State Board of Law"            "Board of Medicine"            

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:42:42