[S] inserting zeroes to make x01, x02, ..., x10, etc.

Jacob A. Wegelin (wegelin@stat.washington.edu)
Thu, 23 Jul 1998 12:24:09 -0700 (PDT)

Often I want a vector of character strings that, when sorted, will appear
in an intuitive order. For instance, if the vector is turned into a
factor, the order affects the organization of a trellis plot.

For instance, if the following vector is sorted, "x10" comes before "x2".

> myfac<-paste("x", 1:10, sep="")

Then the resulting trellis plot has the panels in the wrong order:

> junk<-data.frame(x=rnorm(20), y=runif(20), myfac=rep(myfac,2))
> xyplot( y ~ x | myfac, data=junk)

The function stickInLeadingChar() (appended below) solves this:

or one can say

function(x = c("a", "abd", "", "x"), fillChar = " ", n = max(nchar(x)))
{
# Jacob A. Wegelin, wegelin@stat.washington.edu, July 1998
# Fills up a character vector so all the elements are of the same size, i.e., nchar.
unlist(lapply(x, function(x, n, fillChar)
{
toAdd <- paste(rep(fillChar, n - nchar(x)), collapse = "")
}
, n, fillChar))
}

If anyone has a criticism of this approach I'd read with interest.
I wonder if there's some more elegant or efficient way to solve the
problem.

Thanks

Jacob A. Wegelin
Department of Statistics
University of Washington