s-news
[Top] [All Lists]

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

To: s-news@lists.biostat.wustl.edu
Subject: Re: Padding out a vector of characters to a constant width
From: Glenn.Treacy@ILIM.COM
Date: Mon, 16 May 2005 15:08:14 +0100
Hi,

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?

f.add.leading.chars<-function(jj.vec)
{
        # maximum number of characters
        no.char <- max(nchar(jj.vec))
        # make vector of necessary zeros
        vec <- rep(no.char, length(jj.vec)) - nchar(jj.vec)
        jj.pad <- unlist(lapply(1:length(jj.vec), f.pad, vec = vec, char =
"0"
                ))
        return(paste(jj.pad, jj.vec, sep = ""))
}

 f.pad<-function(x, vec, char)
{
        return(paste(rep(char, vec[x]), collapse = ""))
}

Regards,
Glenn

I am using S+6.2 on NT4


**********************************************************************
This email and any files transmitted with it are confidential and
intended solely for the use of the individual or entity to whom they
are addressed. If you have received this email in error please notify
the system manager.
This footnote also confirms that this email message has been swept 
for the presence of computer viruses.
**********************************************************************


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