String Length


The nchar() function in the base package is used to measure the typical length of the string. One major issues is it’s inability to handle factor values robustly.

nchar('hello world') # Usage of the nchar function.
## [1] 11
factor.Example <- factor(c(1, 1, 0, 0), labels=c("success", "fail"))
nchar(factor.Example) # Using nchar function with factors.
## Error in nchar(factor.Example): 'nchar()' requires a character vector


Alternatively str_length() package could also be used to measure string lengths. In comparisson the str_length() package handles NA characters more accurately as nchar(NA) returns 2 while str_length() returns NA and also handles factor values appropriately.

str_length('hello world') # Usage of the str_length function.
## [1] 11
str_length(factor_example) # Using str_length with factor variables.
## Error in stri_length(string): object 'factor_example' not found