我有一个专栏如下.
9453,55489,4588,18892,4457,2339,45489HQ,7833HQ
如果数字小于5位,我想添加前导零.但是,有些数字到底有"HQ",有些没有.(我确实检查了其他帖子,他们在"HQ"部分没有类似的问题)
所以最终期望的输出应该是:
09453,55489,04588,18892,04457,02339,45489HQ,07833HQ
知道如何做到这一点?非常感谢您阅读我的帖子!
使用正则表达式的单行:
my_strings <- c("9453", "55489", "4588",
"18893", "4457", "2339", "45489HQ", "7833HQ")
gsub("^([0-9]{1,4})(HQ|$)", "0\\1\\2",my_strings)
[1] "09453" "55489" "04588" "18893"
"04457" "02339" "45489HQ" "07833HQ"
Run Code Online (Sandbox Code Playgroud)
说明:
^ start of string
[0-9]{1,4} one to four numbers in a row
(HQ|$) the string "HQ" or the end of the string
Run Code Online (Sandbox Code Playgroud)
括号按顺序表示捕获组.因此0\\1\\2意味着0第一个捕获组[0-9]{1,4}和第二个捕获组HQ|$.
当然,如果有5个数字,那么正则表达式不匹配,所以它不会改变.
我本来打算使用该sprintf方法,但发现该stringr包提供了一个非常简单的解决方案。
library(stringr)
x <- c("9453", "55489", "4588", "18893", "4457", "2339", "45489HQ", "7833HQ")
[1] "9453" "55489" "4588" "18893" "4457" "2339" "45489HQ" "7833HQ"
Run Code Online (Sandbox Code Playgroud)
这可以通过一个简单的stringr::str_pad()函数进行转换:
stringr::str_pad(x, 5, side="left", pad="0")
[1] "09453" "55489" "04588" "18893" "04457" "02339" "45489HQ" "7833HQ"
Run Code Online (Sandbox Code Playgroud)
如果即使总字符串宽度 >5 也需要填充数字,则需要使用正则表达式分隔数字和文本。以下将起作用。它将正则表达式匹配与非常有用的sprintf()函数结合起来:
sprintf("%05.0f%s", # this encodes the format and recombines the number with padding (%05.0f) with text(%s)
as.numeric(gsub("^(\\d+).*", "\\1", x)), #get the number
gsub("[[:digit:]]+([a-zA-Z]*)$", "\\1", x)) #get just the text at the end
[1] "09453" "55489" "04588" "18893" "04457" "02339" "45489HQ" "07833HQ"
Run Code Online (Sandbox Code Playgroud)