首页 > 解决方案 > 在混合字符串之间添加前导零

问题描述

我有一个矢量图

x <- c("MB1",  "MB11" ,"MB12" ,"MB13", "B1",  "B11", "B12", "B13", "B2")

并希望它转换为

x
[1]"MB01"  "MB11" "MB12" "MB13" "B01"  "B11" "B12" "B13" "B02"

x 仅包含“MB”或“B”作为前导字符串,后跟最多两位数。

我知道如何 str_pad,所以我想执行类似的操作

new.vector < paste0("Any Letter you find in each element of x", str_pad("numerical elements of x", 2, pad="0"))

或任何其他方式,可以实现这一点。

谢谢!

标签: r

解决方案


library(tidyverse)

strcapture('([A-Z]+)([0-9]+)', x, 
           proto = list(char = character(), num = numeric())) %>%
  mutate(num = str_pad(num, 2, pad = '0')) %>%
  unite(value, char, num, sep = '') %>%
  pull(value)

#[1] "MB01" "MB11" "MB12" "MB13" "B01"  "B11"  "B12"  "B13"  "B02" 

推荐阅读