Wrap the members of a character vector to a given maximum width by inserting new line characters at word boundaries.
Arguments
- x
character vector, or an object which can be converted to a character vector by
as.character.- width
a positive integer giving the target column for wrapping lines in the output.
- indent
a positive or negative integer giving the indentation of the first line in a member character string.
- new.line
character sting; use
"<br>"for HTML encoded strings.
Value
A character vector of the same length as x, with new line
characters inserted to wrap text lines longer than width. Names in
x are preserved in the returned value, no names are added if none
are present in x.
Details
Function wrap_labels() is a wrapper on link{strwrap}
that returns a vector of character strings instead of a list of vectors. In
addition to wrapping, indentation is supported. Wrapping is always at white
space, so width = 0 wraps word by word.
Because the returned value is a character vector of the same length as the
input, this function can be used within a call to aes() when mapping a
character vector to the label aesthetic, as long as the character
strings will not be parsed into R expressions. It can be also used to wrap
the strings in a variable stored in a data frame.
Examples
my.text <- c(A = "This is the first string",
B = "This is the second string, which is longer")
wrap_labels(my.text, width = 20)
#> A
#> "This is the first\nstring"
#> B
#> "This is the second\nstring, which is\nlonger"
wrap_labels(unname(my.text), width = 20)
#> [1] "This is the first\nstring"
#> [2] "This is the second\nstring, which is\nlonger"
cat(wrap_labels(my.text, width = 20), sep = "\n--\n")
#> This is the first
#> string
#> --
#> This is the second
#> string, which is
#> longer
cat(wrap_labels(my.text, width = 20, indent = 2), sep = "\n--\n")
#> This is the first
#> string
#> --
#> This is the
#> second string,
#> which is longer
cat(wrap_labels(my.text, width = 20, indent = -2), sep = "\n--\n")
#> This is the first
#> string
#> --
#> This is the second
#> string, which is
#> longer
