How to find the length of a string in R

后端 未结 6 1570
遥遥无期
遥遥无期 2020-12-04 05:49

How to find the length of a string (number of characters in a string) without splitting it in R? I know how to find the length of a list but not of a string.

And wha

6条回答
  •  心在旅途
    2020-12-04 05:57

    Use stringi package and stri_length function

    > stri_length(c("ala ma kota","ABC",NA))
    [1] 11  3 NA
    

    Why? Because it is the FASTEST among presented solutions :)

    require(microbenchmark)
    require(stringi)
    require(stringr)
    x <- c(letters,NA,paste(sample(letters,2000,TRUE),collapse=" "))
    microbenchmark(nchar(x),str_length(x),stri_length(x))
    Unit: microseconds
               expr    min     lq  median      uq     max neval
           nchar(x) 11.868 12.776 13.1590 13.6475  41.815   100
      str_length(x) 30.715 33.159 33.6825 34.1360 173.400   100
     stri_length(x)  2.653  3.281  4.0495  4.5380  19.966   100
    

    and also works fine with NA's

    nchar(NA)
    ## [1] 2
    stri_length(NA)
    ## [1] NA
    

提交回复
热议问题