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 a 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.
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.
- Count Number of Occurrences of Certain Character in String
- Count Unique Values in R
- str_count Function of stringr Package
- The R Programming Language
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.
Statistics Globe Newsletter