Count Number of Characters in String in R (2 Examples)
On this page you’ll learn how to get the length of a character string in R programming.
The tutorial will consist of the following:
Here’s the step-by-step process:
Creation of Example Data
First, I’ll need to create some example data:
my_string <- "This is a nice string in R" # Creating character string my_string # Printing character string # "This is a nice string in R"
As you can see based on the previous output of the RStudio console, our example data is a character string stored in the data object my_string.
Example 1: Get Length of Character String Using nchar() Function
In this Example, I’ll illustrate how to find the length of our character string using the nchar function in R. For this task, we have to insert the name of our character string into the nchar command:
nchar(my_string) # Applying nchar function # 26
The RStudio console returns the value 26, i.e. our string consists of 26 characters. Note that blanks are also considered as characters by the nchar function.
Example 2: Get Length of Character String Using str_length() Function of stringr Package
A popular package for the handling and manipulation of character strings in R is the stringr package.
The stringr package also provides functions for the counting of character in strings and in this example I’ll show you how to use those functions in R.
First, we have to install and load the stringr package:
install.packages("stringr") # Install & load stringr library("stringr")
Now, we can apply the str_length function of the stringr package as shown below:
str_length(my_string) # Applying str_length function # 26
The RStudio console returns 26 again, i.e. the result is the same as in Example 1.
Whether you want to use the functions of the base installation of the R programming language or the functions provided by the stringr package is a matter of taste.
Video, Further Resources & Summary
In case you need more information on the contents of this tutorial, you could watch the following video on my YouTube channel. I’m explaining the R programming code of this tutorial in the video.
Furthermore, you may want to read some of the related R tutorials on this website. A selection of related tutorials about topics such as counting, numeric values, and character strings is shown here:
- Count Number of Words in Character String
- Count Number of Occurrences of Certain Character in String
- The R Programming Language
This article explained how to find the amount of characters in a string in the R programming language. Tell me about it in the comments below, in case you have further questions.