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:
> myfac<-paste("x", stickInLeadingChar(1:10), sep="")
or one can say
> myfac<-paste("x", stickInLeadingChar(1:10, "0"), sep="")
"stickInLeadingChar"<-
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 = "")
answer <- paste(toAdd, x, sep = "")
answer
}
, 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
B-313 Padelford
Box 354322
Seattle WA 98195
-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news
|