R: Use nchar(), not length(), for the length of a string

Short note to self: to find the length of a string in R, do NOT use the length() function. A string is secretly a character vector of length 1, so using length() returns the length of the vector:

is.vector("abc")
# [1] TRUE
length("abc")
# [1] 1

To find the length of a string, use the nchar() function (available in base R):

nchar("abc")
# [1] 3

Leave a comment