How to count words in string in R?

In R, you can count the number of words in a string by using the str_count() function from the stringr package. This function takes a character vector and counts the number of words in each string. The result is returned as an integer vector with the same length as the input vector.


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:

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

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.

The following tutorials explain how to perform other common tasks in R:

x