如何将R代码字符串中case后的数字替换为连续升序序列?
问题描述
你有如下R代码字符串:
str <- 'bool rule_cpp(int n, NumericVector x) { bool res = false; switch(n) { case 1: res = x[0] < x[4]; break; case 2: res = x[1] >= x[0]; break; case 3: res = x[3] == x[4]; break; case 1: res = x[0] != x[4]; break; case 2: res = x[1] >= x[0]; break; case 3: res = x[3] <= x[4]; break; case 1: res = x[0] < x[4]; break; case 2: res = x[1] >= x[0]; break; case 11: res = x[0] != x[4]; break; case 2: res = x[1] >= x[0]; break; case 3: res = x[3] <= x[4]; break; case 1: res = x[0] < x[4]; break; case 22: res = x[1] >= x[0]; break; default: stop("Invalid rule number"); } return(res); }'
需要将其中case和:之间的数字替换为连续的升序数字,最终让每个case后的编号从1开始依次递增到13。
你的尝试(未成功)
你尝试了以下代码但未达到预期:
matches <- stringr::str_match_all(str, "case (\\d+):")[[1]][,2] n_cases <- seq_along(matches) new_cases <- paste("case", n_cases, ":") new_str <- gsub(pattern = "case (\\d+):", new_cases, str)
问题分析
你的思路错误在于:gsub函数无法接受一个替换向量来逐个对应替换匹配项,它会将所有匹配到的内容统一替换为new_cases的第一个元素,因此无法实现编号连续递增的效果。
正确实现方法
以下两种方法可以完成需求:
方法一:使用stringr包的回调函数
利用str_replace_all的回调功能,每次匹配时更新计数器,生成对应的新编号:
library(stringr) # 初始化计数器 counter <- 1 # 执行替换 new_str <- str_replace_all(str, "case (\\d+):", function(match) { # 替换匹配字符串中的数字为当前计数器值 updated_case <- str_replace(match, "\\d+", as.character(counter)) # 计数器自增 counter <<- counter + 1 return(updated_case) }) # 输出结果 cat(new_str)
方法二:使用gsubfn包(更简洁)
gsubfn包支持在替换时使用自定义函数,直接生成新的case语句:
library(gsubfn) counter <- 1 new_str <- gsubfn("case (\\d+):", function(x) { current_num <- counter counter <<- counter + 1 paste0("case ", current_num, ":") }, str) # 输出结果 cat(new_str)
两种方法都能生成你需要的连续升序case编号,最终输出的代码会和你预期的效果一致。
内容的提问来源于stack exchange,提问作者mr.T
相关产品推荐
相关产品推荐

