s-news
[Top] [All Lists]

Re: Padding out a vector of characters to a constant width

To: Glenn.Treacy@ILIM.COM
Subject: Re: Padding out a vector of characters to a constant width
From: Alan Zaslavsky <zaslavsk@hcp.med.harvard.edu>
Date: Mon, 16 May 2005 13:30:24 -0400 (EDT)
Cc: s-news@wubios.wustl.edu
> I have a vector characters and I want to padd these out with a fixed
> character so that each element of the vector has the same length.
> 
> If my vector is "A","AA","B","DDD" and my padding character is "X" then I
> want to return the vector "XXA","XAA","XXB","DDD", so each element has a
> length of 3. I have solved this problem with the following two functions but
> I can't help thinking that there must be a simpler method?

pad.leading.chars <- function(x, pad.char)
{
        ## x = character vector
        ## pad.char = string to be repeated to pad (1 or more characters)
                        ## number of characters in shortest and longest strings
minmax.char <- range(nchar(x))
                        ## create the padding string
padding <- paste(rep(pad.char,diff(minmax.char)),collapse="")
                        ## pad it by prepending string of needed length
paste(substring(padding,1,minmax.char[2]-nchar(x)),x,sep="")
}



<Prev in Thread] Current Thread [Next in Thread>