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

如何为以'-'分隔的数据分别给倒数第二位和最后一位数字加1?

处理分隔数字数据的两种方法

首先定义原始数据:

dat <- c("4-3", "60-0 2-5", "10-1 3-2", "20-2 3-0", "3-0", "20-5 3-0")

生成dat1:给每组数字的-前的数字加1

单纯gsub()无法直接对捕获的数字做计算,推荐用gsubfn包实现替换时的数值运算:

# 安装并加载依赖包
install.packages("gsubfn")
library(gsubfn)

# 匹配每组"数字-数字",对-前的数字加1后拼接
dat1 <- gsubfn("(\\d+)-(\\d+)", function(x, y) paste(as.numeric(x)+1, y, sep="-"), dat)

运行后得到dat1:

dat1
# [1] "5-3"          "60-0 3-5"     "10-1 4-2"     "20-2 4-0"     "4-0"          "20-5 4-0"

生成dat2:给每组数字的-后的数字加1

同样用gsubfn处理,这次对-后的数字加1:

dat2 <- gsubfn("(\\d+)-(\\d+)", function(x, y) paste(x, as.numeric(y)+1, sep="-"), dat)

运行后得到dat2:

dat2
# [1] "4-4"          "60-0 2-6"     "10-1 3-3"     "20-2 3-1"     "3-1"          "20-5 3-1"

替代方案:用stringr包实现

如果习惯用stringr,可以通过str_replace_all()配合自定义函数完成:

library(stringr)

# 生成dat1
dat1 <- str_replace_all(dat, "(\\d+)-(\\d+)", function(m) {
  parts <- str_split(m, "-")[[1]]
  paste(as.numeric(parts[1])+1, parts[2], sep="-")
})

# 生成dat2
dat2 <- str_replace_all(dat, "(\\d+)-(\\d+)", function(m) {
  parts <- str_split(m, "-")[[1]]
  paste(parts[1], as.numeric(parts[2])+1, sep="-")
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 19:54:57