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

R语言:如何将数据框字符串列按前3字符拆分为两列?

R字符串拆分:固定前缀+可变长度数字拆分方案

先把你的数据转为数据框:

library(tidyverse)
df <- tibble(code = c("CBR118", "CBR52", "CBR77", "CBR77", "CBR99", "CBR7", "CBR7"))

方法1:用tidyr::separate_wider_regex(推荐)

separate_wider_position不适用是因为你的数字长度不固定,而separate_wider_regex可以通过正则匹配可变长度内容:

df %>%
  separate_wider_regex(
    code,
    patterns = list(prefix = "CBR", num = "\\d{1,3}")
  )

输出结果:

# A tibble: 7 × 2
  prefix num  
  <chr>  <chr>
1 CBR    118  
2 CBR    52   
3 CBR    77   
4 CBR    77   
5 CBR    99   
6 CBR    7    
7 CBR    7    

方法2:基础位置截取

如果不想用正则,直接按字符位置拆分:

df %>%
  mutate(
    prefix = substr(code, 1, 3),
    num = substr(code, 4, nchar(code))
  )

方法3:stringr提取

用字符串匹配分别提取前缀和数字:

df %>%
  mutate(
    prefix = str_extract(code, "^CBR"),
    num = str_extract(code, "\\d+$")
  )

为什么separate_wider_position失败?

这个函数要求拆分的每一部分宽度固定,但你的数字部分长度是1-3位,宽度不统一,所以无法正确拆分,换成正则匹配的方法就能解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 12:03:14