Remove Parentheses in Character String in R (Example)

 

In this R tutorial you’ll learn how to delete parentheses in a character string.

Table of contents:

So now the part you have been waiting for – the example!

 

Creating Example Data

Let’s first create some example data:

my_string <- "aaa (bb) c ()"                    # Create example character string
my_string                                       # Print example character string
# [1] "aaa (bb) c ()"

As you can see based on the previous output of the RStudio console, our example data is a character string containing different letters as well as some parentheses.

 

Example: Remove Parentheses in Character String Using gsub() Function

In this example, I’ll illustrate how to get rid of all round brackets in a character string.

For this task, we can apply the gsub function as shown below. Note that we are wrapping square brackets around the parentheses, since parentheses are considered as special characters by the gsub function:

my_string_new <- gsub("[()]", "", my_string)    # Apply gsub function
my_string_new                                   # Print updated character string
# [1] "aaa bb c "

Have a look at the previous output: We have removed all parentheses from our character string!

By the way, it is also possible to remove parentheses and the text within using the following syntax for the gsub function:

my_string_new2 <- gsub("\\s*\\([^\\)]+\\)", "", my_string) # Also remove text within ()
my_string_new2                                  # Print updated character string
# [1] "aaa c ()"

Note that this code keeps parentheses without text in between.

 

Video & Further Resources

In case you need further explanations on the R programming codes of the present article, you may want to watch the following video on my YouTube channel. I’m explaining the R programming code of this tutorial in the video.

 

Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.

 

Furthermore, you may want to read some of the other articles on my website. You can find a selection of articles below.

 

On this page you have learned how to extract parentheses in a string in the R programming language. If you have additional questions or comments, don’t hesitate to let me know in the comments below.

 

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.


2 Comments. Leave new

Leave a Reply

Your email address will not be published.

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

Menu
Top