Skip to content

Instantly share code, notes, and snippets.

@ateucher
Created May 8, 2014 22:43
Show Gist options
  • Save ateucher/62e6e773a37d1980224c to your computer and use it in GitHub Desktop.
Save ateucher/62e6e773a37d1980224c to your computer and use it in GitHub Desktop.
Insert linebreaks in a string (for wrapping labels)
foldText <- function(x, n) {
x <- gsub(paste0('([^\n]{1,',n,'})(\\s|$)'), '\\1\n', x)
## Remove line-breaks (one or more) at first/last positions
x <- gsub('^(\n)+|(\n)+$', '', x)
x
}
## Examples
txt <- c("Hello my name is Andy",
"Oh when the Saints go marching in",
"The quick brown fox jumped over the lazy brown dog",
"Hi")
foldText(txt,30)
foldText(txt,10)
foldText(txt,2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment