[R] add leading zeros

arun smartpink111 at yahoo.com
Fri Jul 27 14:29:48 CEST 2012


HI Rui,

Not sure how to place the "-" before the zeros.


padz(-5:0,4)
[1] "00-5" "00-4" "00-3" "00-2" "00-1" "0000"
 padz(-(5:0),4)
[1] "00-5" "00-4" "00-3" "00-2" "00-1" "0000"


 formatC(-5:0,width=4,format="d",flag="0")
[1] "-005" "-004" "-003" "-002" "-001" "0000"
padz(1:-10,4)
 [1] "0001" "0000" "00-1" "00-2" "00-3" "00-4" "00-5" "00-6" "00-7" "00-8"
[11] "00-9" "0-10"
 formatC(1:-10,width=4,format="d",flag="0")
 [1] "0001" "0000" "-001" "-002" "-003" "-004" "-005" "-006" "-007" "-008"
[11] "-009" "-010"


A.K.



----- Original Message -----
From: Rui Barradas <ruipbarradas at sapo.pt>
To: LCOG1 <jroll at lcog.org>
Cc: r-help <r-help at r-project.org>
Sent: Friday, July 27, 2012 7:03 AM
Subject: Re: [R] add leading zeros

Hello,

Here is a function that I wrote some time ago.

# pad with zeros
padz <- function(x, width=max(nchar(x)), fill="0")
     gsub(" ", fill, formatC(x, width=width))
##------------- test
padz( c(1, 10, 100) )
padz(1:10, 4)
##------------- non-sense
padz(-5:0, 4)
padz(runif(10))


Hope this helps,

Rui Barradas

Em 27-07-2012 02:08, LCOG1 escreveu:
> Hi all,
>       Trying to use an apply to add leading zeros to a set of values in a
> given vector.  I only want to add enough zeros so that the total number of
> characters is 5, so if I have an element "1" i want "00001" or "9000" I want
> "09000".  I tried
>
> vec <- 1:1000
> sapply(vec, FUN = sprintf(paste("%0",(5-nchar(x)),"d",sep=""),x))
>
> but she doesnt work.  I struggle with the apply family for sure.  Thanks
>
> Josh
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/add-leading-zeros-tp4638031.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list