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")returns13(space counts).nchar(c("cat", "dog", "elephant"))returnsc(3, 3, 8).nchar(123)returns3because R coerces the number to a character string"123".nchar(NA)returnsNA(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 handlesNAthe same way.nzchar()tests whether a string has zero length (returnsTRUEfor non-empty,FALSEfor empty).substr()andsubstring()extract parts of a string, and you often usenchar()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. SettingSys.setlocale("LC_CTYPE", "en_US.UTF-8")can help. - Using
length()instead ofnchar(): As mentioned, this returns the number of vector elements, not characters. - Trailing spaces:
nchar("hello ")returns6because the space counts. If you want to ignore trailing spaces, usetrimws()first. - Empty strings:
nchar("")returns0. - Non-character input:
nchar(TRUE)returns4(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
- SQL Count Duplicates: Find and Group Them
- Shortcut to Duplicate Tab: All Browsers
- Google Sheets Percentage Format: How to Use It
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Copy the Exact Same Formula in Excel Without Changing ItTo copy the exact same formula text in Excel, select the formula in the formula bar, copy it,…
- Return Weekday Dates in Excel: WORKDAY and ExamplesTo return the next weekday date in Excel, use the WORKDAY function. If A2 contains Friday, January 9,…
- Excel MAX IF: Find the Highest Number by ConditionTo find the largest number in Excel that meets a condition, use MAXIFS, such as =MAXIFS(C2:C7,B2:B7,"East"). If you…
- Excel Remove Duplicate Data With a FormulaIn Excel for Microsoft 365, use =UNIQUE(A2:A100) to create a separate list containing each value once; the original…
- How to Indent in the Excel Formula BarTo indent a formula in Excel’s formula bar, edit the formula, insert a line break with Alt+Enter on…
- HLOOKUP in Excel: Sample Formula and ExamplesFor a simple HLOOKUP sample, with years in B1:E1 and revenue in B2:E2, use =HLOOKUP(2025,B1:E2,2,FALSE); it returns the…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.