简体   繁体   中英

Adding leading 0s in r

I have a large data frame that is filled with characters such as:

 x <- c("Y188","Y204" ,"Y221","EP121_1" ,"Y233" , "Y248" ,"Y268", "BB2","BB20",  
 "BB32" ,"BB044" ,"BB056" , "Y234" , "Y249" ,"Y271" ,"BB3", "BB21", "BB33",
 "BB045","BB057" ,"Y236", "Y250", "Y272" , "BB4", "BB22" )

As you can see, certain tags such as BB20 only have two integers. I would like the entire list of characters to have at least 3 integers like this(the issue is only in the BB tags if that helps):

Y188, Y204, Y221, EP121_1, Y233, Y248, Y268, BB002, BB020, BB032, BB044,
BB056, Y234, Y249, Y271, BB003, BB021, BB033, BB045, BB057, Y236, Y250,
Y272, BB004, BB022 

Ive looked into the sprintf and FormatC functions but still am having no luck.

A forceful approach with a nested gsub call:

gsub("(.*[A-Z])(\\d{1}$)", "\\100\\2",
     gsub("(.*[A-Z])(\\d{2}$)", "\\10\\2", x))
# [1] "Y188"    "Y204"    "Y221"    "EP121_1" "Y233"    "Y248"    "Y268"    "BB002"   "BB020"  
# [10] "BB032"   "BB044"   "BB056"   "Y234"    "Y249"    "Y271"    "BB003"   "BB021"   "BB033"  
# [19] "BB045"   "BB057"   "Y236"    "Y250"    "Y272"    "BB004"   "BB022"

There is surely a more general way to do this, but for such a localized task, two simple sub can be enough: add one trailing zero for two-digit numbers, two trailing zeros for one-digit numbers.

x <- sub("^BB(\\d{1})$","BB00\\1",x)
x <- sub("^BB(\\d{2})$","BB0\\1",x)

This works, but will have edge case

# indicator for numeric of length less than three
num <- gsub("[^0-9]", "", x)
id <- nchar(num) < 3

# overwrite relevant values with the reformatted ones
x[id] <- paste0(gsub("[0-9]", "", x)[id],
                     formatC(as.numeric(num[id]), width = 3, flag = "0"))

 [1] "Y188"    "Y204"    "Y221"    "EP121_1" "Y233"    "Y248"    "Y268"    "BB002"   "BB020"   "BB032"  
[11] "BB044"   "BB056"   "Y234"    "Y249"    "Y271"    "BB003"   "BB021"   "BB033"   "BB045"   "BB057"  
[21] "Y236"    "Y250"    "Y272"    "BB004"   "BB022"

It can be done using sprintf and gsub function.This step would extract numeric values and change its format.

num=sprintf("%03d",as.numeric(gsub("[^[:digit:]]", "", x)))

Next step would be to paste back numbers with changed format

x=paste(gsub("[^[:alpha:]]", "", x),num,sep="")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM