> 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="")
}
|