Remove Characters Before or After Point in String in R (Example)


This article shows how to delete characters in a character string before or after a point in the R programming language.

The page is structured as follows:

Let’s start right away!


Creation of Example Data

The following data will be used as basement for this R tutorial:

x <- "aaaa.bbbbbb"          # Create example data
x                           # Print example data
# [1] "aaaa.bbbbbb"

The previous output of the RStudio console shows the structure of the example data – It’s a single character string containing the letters a and b and a point or dot (i.e. “.”) in the middle.


Example: Remove Part Before or After . Using gsub() Function and \\

This example explains how to extract only the part of a character string before or after a point.

Let’s first apply the gsub function as we usually would, in case we want to remove the part of a string before or after a pattern:

gsub("..*", "", x)          # Apply gsub without \\
# [1] ""

As you can see, the RStudio console returns an empty character after running the previous R code.

The reason for this is that the symbol . is considered as a special character. For that reason, we have to use a double backslash in front of the point (i.e. \\).

gsub("\\..*", "", x)        # Apply gsub with \\
# [1] "aaaa"

This works as expected!


Video, Further Resources & Summary

In case you need more info on the R programming codes of this article, you may watch the following video which I have published on my YouTube channel. In the video, I’m explaining the R programming code of this article.


The YouTube video will be added soon.


Besides the video, you may want to have a look at the other tutorials of this homepage. I have released numerous tutorials already:


Summary: In this tutorial, I have explained how to remove characters before or after points in the R programming language. Let me know in the comments, if you have additional questions.


Subscribe to my free statistics 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.