Skip to content
Prev 302762 / 398503 Next

label_wrap_gen question

On 8/8/2012 12:30 AM, vd3000 wrote:
First an etiquette comment: it is customary to quote context when 
replying to the list; nabble does not do this by default (and I don't 
know how to enable it since I don't use nabble). I have restored the 
context (hopefully correctly).

Now to answer your question. If you don't have many labels and you are 
concerned about exactly where the breaks occur, then doing it by hand, 
as you have above, would probably be best. If you want an automated 
solution that respects existing embedded newlines, then you could modify 
the labeller function to do so. Effectively split the strings on 
newlines, then wrap each part, and put them back together, restoring the 
newlines.

label_wrap_respectn_gen <- function(width = 25) {
     force(width)
     function(variable, value) {
       breakn <- strsplit(as.character(value), "\n")
       wrapped <- llply(breakn, strwrap, width=width, simplify=FALSE)
       laply(llply(wrapped, lapply, paste, collapse="\n"),
         paste, collapse="\n")
     }
}

You could roll all this up, since it is simple serial evaluation, but 
that may be harder to read and know what it does:

label_wrap_respectn_gen <- function(width = 25) {
     force(width)
     function(variable, value) {
       laply(llply(llply(strsplit(as.character(value), "\n"),
                         strwrap, width=width, simplify=FALSE),
                   lapply, paste, collapse="\n"),
             paste, collapse="\n")
     }
}

This hasn't been tested extensively, but seem to work for your example.

 > label_wrap <- label_wrap_respectn_gen(width=15)
 > label_wrap(NA, c("Light and heavy good vehicles (diesel) -\nGVX"))
                                                  1
"Light and\nheavy good\nvehicles\n(diesel) -\nGVX"

compared to

 > label_wrap <- label_wrap_gen(width=15)
 > label_wrap(NA, c("Light and heavy good vehicles (diesel) -\nGVX"))
                                                 1
"Light and\nheavy good\nvehicles\n(diesel) - GVX"