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

如何在R语言中检测字符向量各元素是否包含指定子串?

解决方法

问题的核心是原城市字符串包含冗余的州缩写(NY),而目标向量里只有城市核心名称,因此直接匹配会失败。下面提供两种高效的实现方式:

方法1:基础R实现(无需额外包)

先提取城市的核心名称,再用grepl做子串检测:

name <- c("Business Applications for New York", "Proprietors' Farm Income in New York", "Farm Business")
city <- "New York NY"

# 提取城市核心名称(移除末尾的州缩写及前置空格)
city_core <- sub("\\s+[A-Z]{2}$", "", city)
# 或者按空格拆分后取前两个部分(适用于双词城市名)
# city_core <- paste(strsplit(city, "\\s+")[[1]][1:2], collapse = " ")

# 检测每个元素是否包含核心城市名
result <- grepl(city_core, name, fixed = TRUE)
result
# 输出: [1]  TRUE  TRUE FALSE

fixed = TRUE参数会关闭正则解析,让匹配速度更快,适合处理大向量。

方法2:使用stringr包(更简洁)

stringr包的函数更直观,适合字符串处理场景:

library(stringr)

name <- c("Business Applications for New York", "Proprietors' Farm Income in New York", "Farm Business")
city <- "New York NY"

# 移除末尾的州缩写
city_core <- str_remove(city, "\\s+[A-Z]{2}$")
# 检测子串存在性
result <- str_detect(name, fixed(city_core))
result
# 输出: [1]  TRUE  TRUE FALSE

通用扩展说明

如果城市名格式不固定(比如单词城市、多词城市),可以用更灵活的方式提取核心名称,比如取最后一个空格之前的所有内容:

city_core <- str_sub(city, 1, str_locate(city, "\\s+[^\\s]*$")[1] - 1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 16:01:11