Count Number of Words in Character String in R (Example)

 

This post explains how to get the number of words in a character string object in the R programming language.

Table of contents:

Let’s dig in!

 

Creation of Example Data

As first step, I need to define some data that we can use in the examples later on.

x <- "This is my +++ character § string + - Hello"  # Example string
x                                                   # Print string
# "This is my +++ character § string + - Hello"

Have a look at the previous RStudio console output. It shows that our example data is a character string containing several words as well as some special characters.

 

Example: Find Number of Words Using gregexpr & lengths Functions

The following R syntax uses the gregexpr and lengths command to identify the number of words within our exemplifying character string.

lengths(gregexpr("\\W+", x)) + 1                    # Apply gregexpr & lengths
# 6

The RStudio console shows the result: Our character string contains 6 words. Note that the special characters were not counted as words.

 

Video & Further Resources

I have recently published a video on my YouTube channel, which shows the content of the present article. You can find the video below.

 

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 the related tutorials that I have published on statisticsglobe.com.

 

Summary: In this article, I explained how to find the amount of words in a sentence in R. In case you have further questions, please let me know in the comments section. In addition, please subscribe to my email newsletter to receive updates on the newest articles.

 

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.

Menu
Top