Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add leading 0 with gsub

Tags:

r

I would like to add leading zeros to an alphanumeric string for a total of ten characters. It is possible, however, that there is a space in between the characters.

TestID <- c("1b4 7A1")

gsub(" ","0",sprintf("%010s", TestID))

This code adds leading zeros, but also replaces the empty space within the string with a zero. Is there a way to add the zeros only in front of the string?

# [1] "0001b4 7A1"
like image 961
count Avatar asked Dec 18 '15 10:12

count


4 Answers

You could use str_pad from package stringr and do:

str_pad(TestID, width=10, side="left", pad="0")

This gives:

> str_pad(TestID, width=10, side="left", pad="0")
[1] "0001b4 7A1"
like image 169
asachet Avatar answered Sep 18 '22 18:09

asachet


We can use sub

sub('^', paste(rep(0,3), collapse=''), TestID)
#[1] "0001b4 7A1"

If it is to add 0 at the front

paste0('000', TestID)
like image 27
akrun Avatar answered Sep 16 '22 18:09

akrun


A base R solution for strings of variable lengths could be

paste0(paste(rep("0", 10 - nchar(TestID)), collapse=''), TestID)
# [1] "0001b4 7A1"
like image 36
RHertel Avatar answered Sep 20 '22 18:09

RHertel


Can also use the stringi package.

library(stringi)
stri_pad_left(TestID, pad="0", width=10)
# [1] "0001b4 7A1"
like image 28
Ven Yao Avatar answered Sep 17 '22 18:09

Ven Yao