If you would like to loop through a string or check your word count for grad school, you will need to know the length of a string. In this article, we will learn how to get the length of a string in R.
There are two methods to get the length of a string in R. You can use the nchar
or length
method.
nchar("Astrid")
#> [1] 6
You can also use nchar
on a vector of strings and it will return the length of each string.
names = c("Astrid", "Bodil")
nchar(names)
#> [1] 6 5
We can also use the length
function to get the character count. However, we can not use the length
function on a vector in the same way. It will return the length of the vector, not the length of each string.
length("Astrid")
#> [1] 6
names = c("Astrid", "Bodil")
length(names)
#> [1] 2