There are three methods you can use to count the number of words in a string in R:
Method 1: Use Base R
lengths(strsplit(my_string, ' '))
Method 2: Use stringi Package
library(stringi)
stri_count_words(my_string)
Method 3: Use stringr Package
library(stringr) str_count(my_string, '\\w+')
Each of these methods will return a numerical value that represents the number of words in the string called my_string.
The following examples show how to use each of these methods in practice.
Example 1: Count Words Using Base R
The following code shows how to count the number of words in a string using the lengths and strsplit functions from base R:
#create string my_string <- 'this is a string with seven words' #count number of words in string lengths(strsplit(my_string, ' ')) [1] 7
From the output we can see that there are seven words in the string.
Related: How to Use strsplit() Function in R to Split Elements of String
Example 2: Count Words Using stringi Package
The following code shows how to count the number of words in a string using the stri_count_words function from the stringi package in R:
library(stringi) #create string my_string <- 'this is a string with seven words' #count number of words in string stri_count_words(my_string) [1] 7
From the output we can see that there are seven words in the string.
Example 3: Count Words Using stringr Package
The following code shows how to count the number of words in a string using the str_count function from the stringr package in R:
library(stringr) #create string my_string <- 'this is a string with seven words' #count number of words in string str_count(my_string, '\\w+') [1] 7
From the output we can see that there are seven words in the string.
Note that we used the regular expression \\w+ to match non-word characters with the + sign to indicate one or more in a row.
Note: In each of these examples we counted the number of words in a single string, but each method will also work with a vector of strings.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Find Location of Character in a String in R
How to Remove Characters from String in R
How to Select Columns Containing a Specific String in R