<- c("apple", "banana", "cherry") x length(x)
Output:
[1] 3
It is important to distinguish two fundamental concepts, the length of a string vector, and the length of the string itself. The length of a vector refers to the number of elements in that vector. In the following example, we have created a vector of length 3.
<- c("apple", "banana", "cherry") x length(x)
Output:
[1] 3
In contrast, the length of a string refers to the number of characters (e.g., letters, digits, whitespace, special characters) in that specific string, which can be counted by the stringr
function str_length()
.
library(stringr)
# a single element in the vectorstr_length(c("It's a book"))
Output:
[1] 11
# multiple elements in the vectorstr_length(c("a", "bcd", "ef", "It's a book"))
Output:
[1] 1 3 2 11
str_length()
is equivalent to the base R function nchar()
.
nchar(c("a", "bc", "def"))
Output:
[1] 1 2 3