My original request was:
"From an integer, I wish to derive a character string of a specific
width, using leading zeroes as needed. (For example, I would like to
convert 4 to "0004" and 120 to "0120".)"
I so sure that there was an intrinsic way to do this -- as in every other
programming language I've used -- that I completely overlooked the obvious
solution of writing my own function.
I thank the following for replying with solutions: Peter Alspach, Brad
Biggerstaff, Phil Spector, Chuck Taylor, Bill Venables.
----
The most concise method was from Bill Venables:
If all your numbers are known to be less than 10000 you can simply use
zpad <- substring(10000 + num, 2)
----
Phil provided the following more general solution:
"fixint"<- function(n, width)
{
start <- format(n)
paste(c(rep("0", width - nchar(start)), start), collapse = "")
}
---
Peter suggested something similar with an example:
paste(c(rep(0, 4-nchar(4)),4), collapse="")
---
Brad, whose reply reached me no more than 5 minutes from my posting,
suggested the following, which is refined enough to return the number (as
character) even if wider than the specification:
"zero.pad" <-
function(x,n.digits=4){
n <- nchar(as.character(x))
if(n <= n.digits)
leading.zeros <-
paste(rep(0,n.digits-n),sep="",collapse="")
else leading.zeros <- ""
paste(leading.zeros,x,sep="")
}
----
and Chuck had the following functions "lying around" to solve the problem:
"padleft" <- function(x, width = 5, dec = 0, pad = "0", justify = "R")
{
# width = nr of places to left of decimal
left <- trunc(round(x, dec))
if(dec == 0) {
dec.pt <- ""
right <- ""
}
else {
dec.pt <- "."
frac <- x - left
right <- trunc(round(frac, dec) * 10^dec)
nc.r <- nchar(right)
right <- paste(right, genchar(0, dec - nc.r), sep = "")
}
nc.l <- nchar(left)
left <- paste(genchar(pad, width - nc.l), left, sep = "")
paste(left, dec.pt, right, sep = "")
}
"genchar" <- function(x, width)
{
paste(rep(x, width), collapse = "")
}
> padleft(4, 4)
[1] "0004"
> padleft(4, 5)
[1] "00004"
> padleft(120, 4)
[1] "0120"
Again, thanks so much for the immediate and informed responses!
--
Michael Prager, Ph.D. <Mike.Prager@noaa.gov>
NOAA Beaufort Laboratory
Beaufort, North Carolina 28516
http://shrimp.ccfhrb.noaa.gov/~mprager/
|