R string length function: nchar() explained

Formulas & functions · Updated November 23, 2026

The R function for string length is nchar(). It returns the number of characters in a character string, counting each letter, number, space, and punctuation mark individually. For example, nchar("hello") returns 5.

Why nchar() and not length()?

A common mistake for beginners is using length() on a string. In R, length() returns the number of elements in a vector, not the number of characters in a single element. If you have a character vector x <- c("apple", "banana"), length(x) returns 2 (two elements), while nchar(x) returns a vector c(5, 6) (the length of each string). This distinction is crucial for text processing.

Basic usage and examples

The syntax is simple: nchar(x), where x is a character vector or a string. Here are some concrete examples you can run in your R console:

  • nchar("R programming") returns 13 (space counts).
  • nchar(c("cat", "dog", "elephant")) returns c(3, 3, 8).
  • nchar(123) returns 3 because R coerces the number to a character string "123".
  • nchar(NA) returns NA (missing value).

If you need the total number of characters across multiple strings, sum the result: sum(nchar(c("a", "bb", "ccc"))) returns 6.

Handling missing values and factors

By default, nchar() returns NA for missing values. If you want to treat NA as 0 characters, use the argument keepNA = FALSE: nchar(NA, keepNA = FALSE) returns 0. For factor variables, R will use the underlying character labels, not the integer codes. For example, nchar(factor("apple")) returns 5 because it works on the label “apple”, not the internal integer.

Counting bytes vs characters

Sometimes you need the number of bytes, especially when working with file sizes or encodings. The nchar() function has a type argument: type = "chars" (default) counts characters, type = "bytes" counts bytes, and type = "width" counts the display width (useful for monospaced fonts). For ASCII text, characters and bytes are the same. For non-ASCII text like emojis or accented letters, they differ. Example: nchar("é") returns 1 (one character), but nchar("é", type = "bytes") may return 2 if the system uses UTF-8 encoding. This matters when writing files or sending data over networks.

String length in other R functions

While nchar() is the primary function, related tasks often use other tools:

  • str_length() from the stringr package does the same thing but is more consistent with the tidyverse style and handles NA the same way.
  • nzchar() tests whether a string has zero length (returns TRUE for non-empty, FALSE for empty).
  • substr() and substring() extract parts of a string, and you often use nchar() to determine the end position.
  • strtrim() trims a string to a specified width, which internally uses character counts.

For example, to get the last three characters of a string, you can use substr(x, nchar(x) - 2, nchar(x)).

Common pitfalls and errors

Several issues trip up new users:

  • Encoding issues: If your system locale is not UTF-8, nchar() might return unexpected results for non-ASCII characters. Setting Sys.setlocale("LC_CTYPE", "en_US.UTF-8") can help.
  • Using length() instead of nchar(): As mentioned, this returns the number of vector elements, not characters.
  • Trailing spaces: nchar("hello ") returns 6 because the space counts. If you want to ignore trailing spaces, use trimws() first.
  • Empty strings: nchar("") returns 0.
  • Non-character input: nchar(TRUE) returns 4 (the string “TRUE”). Be aware of coercion.

If you get an error like “‘nchar’ requires a character vector”, check that your variable is not a list. Use as.character() to convert if needed.

Performance and vectorization

nchar() is vectorized, meaning it works on entire vectors at once. This is efficient for large datasets. For example, if you have a data frame with a column of text, you can add a column of lengths using df$len <- nchar(df$text). This is much faster than looping with for or apply. For extremely large datasets (millions of rows), nchar() is still fast because it is implemented in C. If you need to process strings in a loop, consider using vapply or sapply to avoid side effects, but vectorization is preferable.

Frequently Asked Questions

How do I count characters excluding spaces?

Use gsub() to remove spaces first, then nchar(). For example, nchar(gsub(" ", "", "hello world")) returns 10 instead of 11. You can also use str_remove_all() from stringr if you prefer.

Why does nchar() return NA for missing values?

Because NA represents an unknown value, and the length of an unknown string is unknown. If you want to treat missing as empty, use nchar(x, keepNA = FALSE) which returns 0 for NA.

What is the difference between nchar() and str_length()?

Functionally, they are identical for most purposes. str_length() is from the stringr package and is designed to be more consistent with the tidyverse philosophy. It also returns NA for missing values. The main difference is that str_length() does not have a type argument; it always counts characters, not bytes.

How can I find the longest string in a vector?

Use which.max(nchar(x)) to get the index, then x[which.max(nchar(x))] to get the string. For example, fruits <- c("apple", "banana", "strawberry"); fruits[which.max(nchar(fruits))] returns "strawberry".

Does nchar() count emojis correctly?

In most modern R versions with UTF-8 encoding, nchar() counts an emoji as one character, even though it may be stored as multiple bytes. However, some complex emojis (like those with skin tone modifiers) may be counted as multiple characters depending on the OS and R version. If you need precise handling, consider using the stringi package’s stri_length() which is more robust for Unicode.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.