[R] Leading zeros

Peter Langfelder peter.langfelder at gmail.com
Fri Aug 19 18:33:12 CEST 2011


On Fri, Aug 19, 2011 at 9:19 AM, David Winsemius <dwinsemius at comcast.net> wrote:
>
> Copying list one what was sent in reply. Anybody have a better solution?
>

No sure my solution is better, but it avoids the integer conversion
and retains the "/".
I wrote a function that padds entries of input character vector with
zeros to final length 'length'.

padZeros = function(x, length)
{
  n = length(x);
  out = rep("", n);
  for (i in 1:length(x))
  {
    l = nchar(x[i]);
    out[i] = paste( paste(rep("0", length-l), collapse = ""), x[i], sep = "");
  }
  out
}

> padZeros(c("33/22", "4/50005", "6644/2233"), length = 12)
[1] "000000033/22" "000004/50005" "0006644/2233"

HTH,

Peter



More information about the R-help mailing list