On Thu, 2007-12-06 at 09:28 -0800, Jim Price wrote:
> I wrote a little utility function for exactly this reason, which I use with
> long titles. You may want to add calls to par to adjust the upper margin if
> you are using raw graphical functionality (plot et al) - but lattice adjusts
> the upper margin automatically so you wouldn't need to add anything else.
> 
> 
> PrettyString <- function(theString, maxLength, collapse = "\n")
> {
>       words <- unlist(strsplit(theString, " "))
>       wordLengths <- unlist(lapply(strsplit(words, ""), length))
> 
>       if(max(wordLengths) > maxLength) 
>               stop("maxChar must be increased due to string length")
> 
>       count = wordLengths[1]
>       results = vector()
>       currentLine = words[1]
> 
>       for(i in 2:length(words))
>       {
>               if((count + wordLengths[i] + 1) > maxLength)
>               {
>                       results = c(results, currentLine)
>                       currentLine = words[i]
>                       count = wordLengths[i]
>               }
>               else
>               {
>                       currentLine = paste(currentLine, words[i])
>                       count = count + wordLengths[i] + 1
>               }
>       }
>       if(length(currentLine))
>               results <- c(results, currentLine)
> 
>       paste(results, collapse = collapse)
> }
> 
> 
> Knowing the R list, someone can probably reduce this function to 2 lines of
> code.
> Jim

Would you believe one line?

  paste(strwrap(theString, width = maxLength), collapse = "\n")

;-)

See ?strwrap as I noted previously.

HTH,

Marc Schwartz

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to