Peter Pan
Peter Pan

Reputation: 65

How to use sprintf function to add leading "0" instead of spaces to character?

I am trying to use sprintf function to add leading "0" to character, and make all charaters the same length. However what I get is leading space.

My code:

a <- c("12","123", "1234")
sprintf("%04s",a)
[1] "  12" " 123" "1234"

What I tried to get:

[1] "0012" "0123" "1234"

The sprintf manual says: "For characters, this zero-pads on some platforms and is ignored on others."

My version: platform x86_64-w64-mingw32
arch x86_64
os mingw32
system x86_64, mingw32
status
major 3
minor 1.0
year 2014
month 04
day 10
svn rev 65387
language R
version.string R version 3.1.0 (2014-04-10) nickname Spring Dance

Upvotes: 3

Views: 2952

Answers (1)

Carl Witthoft
Carl Witthoft

Reputation: 21502

If you are on a platform which only inserts spaces, regex is your friend. Something like

foo<- gsub('^[ ]{1,}','0',bar)

That will replace all leading spaces with a 0 . I know regex can be told to replace N spaces with N zero-chars, but I forget exactly how.

EDIT: to those paste0 naysayers, how about:

wantlength <- 12 # the desired final string size, fully zero padded
paste0( paste0(rep('0',wantlength-nchar(foo)),collapse='') ,foo)

Upvotes: 2

Related Questions