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

如何使用purrr::map()重写示例中的for循环实现字符串修正

实现方案

你的需求本质是依次应用多组字符串替换规则,前一轮的输出作为后一轮的输入,属于累积迭代场景,用purrr::reduce()比普通map函数更适配,实现代码如下:

library(purrr)

# 原始数据
vct_string <- c("old ccar","new carr", "house", "oold house")
df_correction <- data.frame(
  pattern  = c("ccar", "carr", "oold"),
  replacement = c("car", "car", "old"),
  stringsAsFactors = FALSE
)

# 替换实现
vct_string_corrected <- reduce(
  .x = transpose(df_correction),
  .f = \(current_str, rule) gsub(rule$pattern, rule$replacement, x = current_str),
  .init = vct_string
)

# 输出验证
vct_string_corrected
#> [1] "old car"   "new car"   "house"     "old house"

逻辑说明

  1. 先用transpose(df_correction)把校正规则数据框转成按行拆分的列表,每个元素对应一组pattern和replacement规则
  2. reduce从初始值.init(即原始字符串向量)开始,逐次将每一条规则应用到当前的字符串结果上,最终输出和示例for循环完全一致的结果

如果你一定要用map系列函数实现也可以,但是逻辑可读性更差,需要用到全局变量赋值,不推荐日常使用,仅做参考:

res <- vct_string
walk(pmap(df_correction, list), \(rule) {
  res <<- gsub(rule[[1]], rule[[2]], x = res)
})

内容的提问来源于stack exchange,提问作者Leonardo Donato Nunes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 17:42:01