tidyverse / stringr

A fresh approach to string manipulation in R
https://stringr.tidyverse.org
Other
603 stars 187 forks source link

[Feature request] allow `str_wrap()` to wrap into n segments of equal length #572

Open DanChaltiel opened 1 month ago

DanChaltiel commented 1 month ago

Hi,

When using str_wrap() for plot captions, it is often useful to fix the number of lines rather than the number of characters per line.

For that, I'm using the following code:

library(tidyverse)

caption = "The dots and whiskers represent the median and the 25th and 75th percentiles of the X coefficient among the N simulated trial replicates."

p = ggplot(mtcars, aes(x=disp, y=disp)) +
  geom_point() +
  coord_fixed()  

p + labs(caption=caption) #the caption overflows

p + labs(caption=str_wrap(caption, nchar(caption)/2))

Created on 2024-09-04 with reprex v2.1.1

However, as you can see, you need to refer to the caption object twice, which is not handy, and the output is not perfect when the split happens near long words (the output has 3 lines instead of 2, don't have a workaround for that yet).

Do you think str_wrap() could support an additional argument to specify the number of lines instead of width?