str_trim Function in R (Example)

 

This tutorial illustrates how to use str_trim to trim whitespace from a character string in the R programming language.

The content of the article is structured as follows:

Let’s do this!

 

Creation of Example Data

Let’s first create a character string, which contains some white space at the beginning and at the end.

x <- "    a  aaa  "             # Create a character string

To enable the application of the str_trim command, we also need to install and load the stringr package of the tidyverse environment to R:

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

Keep on reading, we are now moving on to the exemplifying application of str_trim.

 

Example: str_trim Function in R

If we want to trim leading and trailing whitespace in R, we can use the str_trim function as shown below:

str_trim(x)                     # Apply str_trim function
# "a  aaa"

As you can see based on the quotation marks of the previous output of the RStudio console, we removed all blanks at the beginning and at the end of our character string.

 

Video, Further Resources & Summary

Do you need more explanations on the R programming code of this article? Then you could have a look at the following video which I have published on my YouTube channel. I’m explaining the topics of this tutorial in the video.

 

The YouTube video will be added soon.

 

In addition, you may read the related articles of this homepage.

 

In summary: In this tutorial, I showed how to remove blanks from a character string in the R programming language. If you have further questions, don’t hesitate to let me know in the comments below. Furthermore, please subscribe to my email newsletter to receive regular updates on new tutorials.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


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.

Top