0

I have a set of strings such as

x <- c("xxx", "xxx xxx", "xxx xxxx xxx", "xxx xxxx xxx xxxxxx")

and I want to wrap each so that they fall over two lines, with the breaks where there are spaces, roughly in the middle of the strings, i.e. an output such as

"xxx" "xxx\nxxx" "xxx\nxxxx xxx" "xxx xxxx\nxxx xxxxxx"

I thought strwrap would work, but I cannot figure out how set a width that does will avoid outputs straying on to a third line

guyabel
  • 8,014
  • 6
  • 57
  • 86

1 Answers1

1

I don't know of any built in function that does this, but you can find the "middle-most" space and replace it with a new line with a function like this:

two_line_wrap <- function(x) {
  mapply(function(spaces, length, string) {
    if(all(spaces==-1)) return(string);
    breakp <- spaces[which.min(abs(spaces-length/2))]
    substr(string, breakp, breakp) <- "\n"
    string
  }, gregexpr(" ", x), nchar(x), x)
}

two_line_wrap(x)
# [1] "xxx"                  "xxx\nxxx"            
# [3] "xxx\nxxxx xxx"        "xxx xxxx\nxxx xxxxxx"
MrFlick
  • 195,160
  • 17
  • 277
  • 295