Count the number of characters in R with nchar
You can count the number of characters of a string or character vector with the nchar
function and check if a string is empty or not with nzchar
. In this tutorial we will review both functions and their use cases.
The nchar
function
If you want to count the number of characters of a string you can use the nchar
function, as shown in the example below.
nchar("Sample string")
13
The function also admits a vector as input and will return the number of characters of each of the elements of the vector.
nchar(c("1st element", "Element 2", "Third element"))
11 9 13
Note that, by default, the function will return an NA
if any of the elements is a missing value.
nchar(c("1st element", "Element 2", NA, "Fourth element"))
11 9 NA 14
However, if you set keepNA = FALSE
the NA
value will be treated as a string and the function will return 2.
nchar(c("1st element", "Element 2", NA, "Fourth element"),
keepNA = FALSE)
11 9 2 14
The nzchar
function
The nzchar
function returns a logical vector of the same length as the input whose elements will be TRUE
if the corresponding character is a non-empty string or FALSE
otherwise.
nzchar(c(NA, "", "string"))
TRUE FALSE TRUE
The NA
values are considered by default as non-empty strings, so if you want to keep the missing values just add keepNA = TRUE
as in the example below.
nzchar(c(NA, "", "string"), keepNA = TRUE)
NA FALSE TRUE