To find the length of the string in R, use the nchar() or length() function. The length() function is used to find a length to any R Object, while the nchar() function is used to find a length of a character vector. In this tutorial, we will see how to get the size of vector elements in R programming.
nchar() in R
To get the size of each element of a character vector in R, use the nchar() function. The nchar() function counts the number of characters (or Bytes or Width). The nchar() method takes a character vector as an argument and returns the vector whose items contain the sizes of the corresponding items of the input character vector object.
nchar(x, type = "chars", allowNA = FALSE)
x: It is a character vector.
type: It is bytes, chars, or width.
allowNA: logical: should NA be returned for invalid multibyte strings or “bytes”-encoded strings (rather than throwing an error)?
The nchar() function returns an integer vector giving the sizes of each element. For missing values, for example, NA values, the nchar() function returns NA_integer_ if keepNA is TRUE, and the number of printing characters, if FALSE.
data <- c("PS5", "XBOX Series X", "Nintendo Switch") nchar(data)
 3 13 15
In this example, the nchar() function returns the character length of each element of the character vector. For example, PS5 has 3 characters, XBOX Series X has 13, and so on.
Passing NA values to the nchar() function
The nchar() function provides an optional argument called keepNA, which can be helpful when dealing with NA values.
data <- c("", NULL, "Aloh Mora", NA) nchar(data, keepNA = FALSE)
 0 9 2
The first component is empty, so it returns 0, and the second is NULL, so it does not return anything, the third is a string that contains 9 characters, and the last is NA value. We got 2 because we have passed keepNA = FALSE. If we pass keepNA = TRUE, then see the following output.
data <- c("", NULL, "Aloh Mora", NA) nchar(data, keepNA = TRUE)
 0 9 NA
As you can see from the output, it keeps the NA value in the output since we have passed keepNA = TRUE.
nzchar() Function in R
The nzchar() is an inbuilt function that tests whether elements of a character vector are non-empty strings.
The nzchar() function takes the character vector x as a parameter.
It returns the boolean value either TRUE or FALSE.
Let’s define a character vector and tests whether elements of the vectors are non-strings or not.
data <- c("Avada Kedavara", "Crucio", "Expecto Patronum") nzchar(data)
 TRUE TRUE TRUE
In this example, all the vector elements are non-empty strings. So it returns TRUE to all the elements.
Test the following.
data <- c("", "Aloh Mora", "") nzchar(data)
 FALSE TRUE FALSE
As you can see from the output that if the character element is empty, then it returns FALSE otherwise TRUE. The nzchar() function is the fastest way to determine if components of a character vector are non-empty strings.
That is it for this tutorial.