nchar
nchar counts how many letters are in a piece of text, like counting the beads on a necklace. It works on a whole list of words at once too.
In this page:
Syntax
nchar(string_or_vector)
nchar
nchar() returns the number of characters in a string, and applied to a vector of strings, it returns a vector of lengths. It's the R equivalent of a string-length function found in most languages.
This is different from length(), which for a single string returns 1 (since a string is a vector of length 1 containing one character element).
Warning:
length("hello") returns 1 (it's a vector containing one string), not 5 -- use nchar() to get the character count.
Example: nchar
text <- "Hello, R!"
cat(nchar(text), "\n")
cat(length(text), "\n") # this is 1, not the character count
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
length(text)to count characters, which gives1for a single string; usenchar(text). - Expecting
nchar(NA)to be0, when it is2for a logicalNAandNA_integer_for characterNA. - Forgetting that
ncharcounts characters, not bytes, unlesstype = "bytes"is set.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: