r - 在混合字符串之间添加前导零
问题描述
我有一个矢量图
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"))
或任何其他方式,可以实现这一点。
谢谢!
解决方案
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"
推荐阅读
- android - 生成 apk 时无法识别库
- python - 点击远离 tkinter.Enrry
- python - 反复构造和销毁上下文会报错 #1260
- php - Laravel 迁移不指定列类型
- javascript - 错误:JSON.parse 中位置 0 处的 JSON 中的意外标记 <
) 在 XMLHttpRequest.ajax.onreadystatechange - spring-boot - 当我升级到 Vue 2.6.0 时,为什么会收到“SyntaxError:字符类中的无效范围”?
- docker - Dockerfile COPY 从主机到容器有效,但是当 docker-compose.yml 使用卷时,容器中的文件对主机不可见
- sas - 用于 SAS 的 %CEM 宏:指定用于匹配的变量
- node.js - Node/Express:解压缩目录时模拟 req.files
- vbscript - 检查多台机器上正在运行的进程