str_wrap Function in R (Example)


In this R programming tutorial you’ll learn how to apply the str_wrap function to wrap a character string into nicely formatted paragraphs.

The content of the post looks as follows:

So now the part you have been waiting for – the programming part.


Creation of Example Data

In this R tutorial, I’ll use the following character string:

x <- "heyho I am a very long string"    # Create a character string

Furthermore, we have to install and load the stringr package of Hadley Wickham’s tidyverse environment to R:

install.packages("stringr")             # Install stringr R package
library("stringr")                      # Load stringr R package


Example: str_wrap Function in R

We can wrap our character string into nicely formatted paragraphs as follows:

str_wrap(x, 10)                         # Apply str_wrap function
# "heyho\nI am a\nvery long\nstring"

Have a look at the previously shown RStudio console output. We just inserted three times the pattern “\n” into our character string, leading to well formatted paragraphs whenever we export our data.


Video, Further Resources & Summary

Would you like to know more about the stringr package and the handling of character strings in R? Then I can recommend to have a look at the following video of my YouTube channel. In the video, I’m explaining the examples of this tutorial in a live programming session.


The YouTube video will be added soon.


Furthermore, you may want to have a look at the related R programming articles of this homepage. A selection of tutorials is shown below.


Summary: In this R post you learned how to convert character strings into well formatted chunks of paragraphs. If you have additional questions, tell me about it in the comments. Besides that, please subscribe to my email newsletter to get regular updates on the newest articles.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.