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

R语言中如何为分号后的内容添加对应前缀文本?

解决方法:为分号后内容添加对应前缀

原始数据构造

先明确带列名的原始数据框(方便后续操作):

test1 <- data.frame(col = c("ABC 01; 02; 03", "test2 01; 02; 03"))

方法一:Base R 通用处理(适配任意数量分号分隔项)

通过字符串拆分、提取前缀、重新拼接实现,不管每行有多少个分号分隔的数字都能处理:

test1$col <- sapply(strsplit(test1$col, "; "), function(x) {
  # 从第一个元素提取前缀(去掉末尾的数字部分)
  prefix <- sub(" \\d+$", "", x[1])
  # 给每个元素补上前缀后重新拼接
  paste(paste(prefix, sub(paste0("^", prefix, " "), "", x)), collapse = "; ")
})

方法二:Base R 固定格式匹配(适用于固定3个项的情况)

如果每行字符串格式固定为「前缀 数字; 数字; 数字」,可以用正则反向引用快速处理:

test1$col <- gsub("^(\\w+) (\\d+); (\\d+); (\\d+)", "\\1 \\2; \\1 \\3; \\1 \\4", test1$col)

方法三:tidyverse 工具链处理

使用stringr包的字符串函数实现,更贴合tidy风格:

library(tidyverse)

test1 <- test1 %>%
  mutate(
    # 提取每行的前缀
    prefix = str_extract(col, "^\\w+"),
    # 替换分号后的数字为「前缀 数字」格式
    col = str_replace_all(col, "; (\\d+)", paste0("; ", prefix, " \\1")),
    # 删除临时前缀列
    prefix = NULL
  )

最终结果

执行任意方法后,数据框内容如下:

print(test1)
#                  col
# 1 ABC 01; ABC 02; ABC 03
# 2 test2 01; test2 02; test2 03

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:35:13