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.
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.
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.
Thank you!
Welcome to the Statistics Globe newsletter. From now on, I’ll send you regular emails about statistics, data science, AI, and programming with R and Python.
I’m Joachim Schork. On this website, I provide statistics tutorials as well as code in Python and R programming.
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.
Thank you!
Please check your email inbox and click the confirmation link to complete your subscription. If you don’t see the email within a few minutes, please also check your spam/junk folder.






