Trim Leading and Trailing Whitespace in R (Example for trimws Function)
This tutorial explains how to remove leading and trailing whitespace in the R programming language.
The article is mainly based on the trimws() R function. Let’s have a look at the basic R syntax and the definition of trimws() first:
Basic R Syntax of trimws():
Definition of trimws():
The following article explains in an actionable examples how to trim leading and trailing whitespace with the trimws command in R.
Let’s dive in!
Step 1: Create Example Data
Before we can apply the trimws function, we need to create some example data:
my_text <- " . abcd e f " # Create example character string my_text # Print example data to RStudio console # " . abcd e f "
Based on the output of the RStudio console you can see that our example data is a simple character string with leading AND trailing spaces. Now let’s remove this whitespace…
Step 2: Remove Leading and Trailing Whitespace
We can delete leading and trailing whitespace with the trimws function as follows:
trimws(my_text) # Apply trimws function in R # ". abcd e f"
Based on the quotation marks of the output you can see that the whitespace was removed. Looks good!
Video & Further Resources
I have recently published a video on my YouTube channel, which explains the previous example in more detail. So if you want to learn more about the trimming of whitespace in front and after your character strings you might have a look at the video:
Furthermore, you may read the other R tutorials on my website. Some interesting tutorials are listed below:
At this point you should be able to trim trailing and leading blanks in the R programming language. However, let me know in the comments in case you have any further questions.