Wrapping

We wish to format a string as a paragraph with a certain line width. In other words, we wish to insert a newline character at a given line width (in number of characters). This is often useful for display purposes e.g. in notebooks or web apps.

df_2 = df %>%
  mutate(col_2 = str_wrap(col_1, width = 10))

Here is how this works:

  • We use the str_wrap() function from the stringr package (part of the tidyverse) to wrap the values in the column col_1 into a paragraph where each line has a maximum width of 10 characters.
  • The str_wrap() function takes the following arguments:
    • The column whose values we wish to wrap; which in this case is col_1.
    • A named argument width that specifies the target line width.
  • Two points to note about wrapping via str_wrap():
    • New lines are inserted only between words.
    • If a word is longer than the width, the word will not be broken and no new line will be added. Therefore, the output may exceed the specified line width.
  • The output data frame df_2 will have the same number of rows as the original data frame df but with an additional columncol_2 holding the wrapped version of the column col_1.
R
I/O