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

如何在字符串中查找特定关键词并替换?含R语言DataFrame示例

没问题,我来帮你搞定在R语言DataFrame里的字符串查找替换操作!针对你的数据集,我给你两种常用的实现方式,你可以根据自己的习惯选择:

方法一:用Base R自带的gsub()/sub()函数

Base R里的gsub()是处理全局替换的利器——它会把目标字符串里所有匹配到的关键词都替换掉;如果只需要替换每个字符串里的第一个匹配项,就用sub()。

举个具体的例子,假设你想把所有的"Beam calibration"替换成"Beam Calibration (Completed)",代码如下:

# 先还原你的原始数据(避免之前的修改影响)
ID <- c("A112","A114","A134","A116","A117","A138")
Comment <- c("Beam calibration again", "Beam calibration. Tools ready", "Did not find anything wrong. Beam calibration","Performed beam calibration. tool ready", "STD Qual and Blurry image looks fine","STD Qual failed and Slightly Blurry image")
df<- data.frame(ID,Comment)

# 全局替换所有匹配的关键词
df$Comment <- gsub(pattern = "Beam calibration", replacement = "Beam Calibration (Completed)", x = df$Comment)

# 查看替换后的结果
print(df)

如果需要不区分大小写替换(比如把"tool"和"Tools"都换成"Equipment"),只需要给gsub()加个参数:

df$Comment <- gsub(pattern = "tool", replacement = "Equipment", x = df$Comment, ignore.case = TRUE)
方法二:用stringr包(tidyverse生态)

如果你平时习惯用tidyverse系列工具,stringr包的字符串操作函数会更直观易读。str_replace_all()对应全局替换,str_replace()对应单个匹配替换。

先安装并加载包:

install.packages("stringr") # 第一次用需要安装
library(stringr)

同样的替换需求,用stringr实现的代码:

# 全局替换"Beam calibration"
df$Comment <- str_replace_all(df$Comment, "Beam calibration", "Beam Calibration (Completed)")

# 不区分大小写替换所有"tool"相关内容
df$Comment <- str_replace_all(df$Comment, regex("tool", ignore_case = TRUE), "Equipment")

两种方法都能达到目的,你可以根据自己的代码风格选择~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:38:08