To get the length of a String in R, there are many ways to do that, but the most appropriate way is using the nchar() function. But you feel free to use other methods described in this article.
How to Find Length of String in R
To find the length of a String in R, use the nchar() function. The nchar() is a built-in R function that counts the number of characters (or Bytes or Width) in a String.
The nchar() function accepts x as an argument which is a character data type.
Let’s define a variable with a String value and find its length using the nchar(string) function.
str <- "Sheldon Lee Cooper!" # find length using nchar(str) lnth <- nchar(str) print(lnth)
As you can see that the string “Sheldon Lee Cooper!” has 19 characters, and that is why the length of a string is 19.
You can use the nchar(c) method for other data types to find the length. Let’s find the Length of a Number in R.
num <- 110470116021 # find length using nchar(c) length <- nchar(num) print(length)
There is another way to find out the length of the string using R lang’s third-party library.
stringr library in R
The stringr library is built on top of stringi, which uses the ICU C library to provide fast, correct implementations of common string manipulations.
To find out the length of the string using the stringr library, use the str_length() function and pass the string as an argument.
library(stringr) str_length("Sheldon Lee Cooper!")
The str_length() function takes a vector of strings as input and returns the number of characters in each string.
Difference between nchar() and str_length()
The main difference between the base function nchar() and str_length() function is that the str_length() method intuitively handles factors, whereas the nchar() method will return an error.
The nchar() function returns an error if you passed it a factor; it would return the number of characters in the numeric encoding of the factor. Fortunately, this behavior has been fixed, but it was the main motivation behind the str_length() function.
Using a length in combination with the unlist() and strsplit()
str <- "Sheldon Lee Cooper!" length(unlist(strsplit(str, "")))
And we get the length of the string, but this method is not recommended since it takes too much time to process it.
That’s it for this tutorial.