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

如何用grepl匹配指定字符串并排除其他?R语言正则问题

解决方案

要实现这个需求,核心是做精确匹配而非部分匹配,所以正则里要加上字符串首尾锚点^和$,确保只有当Ingredient完全等于指定值时才返回TRUE。

正则表达式说明

使用^salt$|^sodium chloride$:

  • ^:匹配字符串的开头
  • $:匹配字符串的结尾
  • |:逻辑“或”,分隔两个需要精确匹配的目标值

这样就能避免把包含"salt"但不是目标值的字符串(比如salt replacer、unsalted)误判为TRUE。

完整代码

# 原始数据框
df <- data.frame(
  Food = c("Apple", "Banana", "Carrot", "Donut", "Eclair", "Flour"),
  Ingredient = c("salt", "sodium chloride", "salt replacer", "unsalted", "veg salt", "vegetable salt")
)

# 添加Salt_Present列
df$Salt_Present <- grepl("^salt$|^sodium chloride$", df$Ingredient)

# 查看结果
df

运行结果

FoodIngredientSalt_Present
ApplesaltTRUE
Bananasodium chlorideTRUE
Carrotsalt replacerFALSE
DonutunsaltedFALSE
Eclairveg saltFALSE
Flourvegetable saltFALSE

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 05:35:08