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

如何在R语言向量中含指定模式的字符串前插入指定字符串

解决方案:在含指定关键词的字符串前插入元素

针对你的需求,这里提供几种实用的R语言实现方式:

方法一:基础循环(直观易懂)

这种方式逻辑简单,适合新手理解,直接遍历每个元素,遇到含"formula"的字符串时,先将"CCC"加入结果,再加入当前字符串:

test <- c("here is some text", "here is some other text", "here is my formula", "2+2", "here is my second formula", "4+4", "here is even more text", "here is my final formula", "6+6")

result <- c()
for (str in test) {
  if (grepl("formula", str)) {
    result <- c(result, "CCC", str)
  } else {
    result <- c(result, str)
  }
}

# 输出结果
print(result)

方法二:向量索引操作(高效无循环)

如果处理的向量规模较大,循环会有性能损耗,可以用向量索引的方式实现,避免循环:

test <- c("here is some text", "here is some other text", "here is my formula", "2+2", "here is my second formula", "4+4", "here is even more text", "here is my final formula", "6+6")

# 标记所有包含"formula"的元素
needs_insert <- grepl("formula", test)
# 计算最终结果向量的长度
final_length <- length(test) + sum(needs_insert)
# 初始化结果向量
result <- character(final_length)

# 计算原元素在结果向量中的位置
original_pos <- cumsum(rep(1, length(test)) + needs_insert) - needs_insert
# 填充原元素
result[original_pos] <- test
# 填充插入的"CCC"到对应位置
result[setdiff(1:final_length, original_pos)] <- "CCC"

# 输出结果
print(result)

方法三:tidyverse风格(简洁优雅)

如果你熟悉tidyverse工具集,可以用purrr包的函数实现更简洁的代码:

library(purrr)

test <- c("here is some text", "here is some other text", "here is my formula", "2+2", "here is my second formula", "4+4", "here is even more text", "here is my final formula", "6+6")

result <- test %>%
  map(function(x) if (grepl("formula", x)) c("CCC", x) else x) %>%
  flatten_chr()

# 输出结果
print(result)

以上三种方法都能得到你想要的结果,可根据自己的代码习惯和数据规模选择合适的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:33:37