R count number of commas and string

前端 未结 4 927
遇见更好的自我
遇见更好的自我 2021-01-17 19:25

I have a string:

    str1 <- \"This is a string, that I\'ve written 
        to ask about a question, or at least tried to.\"

How would

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-17 19:47

    Another option is stringi

    library(stringi)
    stri_count(str1,fixed=',')
    #[1] 2
    stri_count(str1,fixed='ion')
    #[1] 1
    

    Benchmarks

    vec <- paste(sample(letters, 1e6, replace=T), collapse=' ')
    f1 <- function() str_count(vec, 'a')
    f2 <- function() stri_count(vec, fixed='a')
    f3 <- function() length(gregexpr('a', vec)[[1]])
    
    library(microbenchmark)
    microbenchmark(f1(), f2(), f3(), unit='relative', times=20L)
    #Unit: relative
    #expr      min       lq     mean   median       uq      max neval cld
    # f1() 18.41423 18.43579 18.37623 18.36428 18.46115 17.79397    20   b
    # f2()  1.00000  1.00000  1.00000  1.00000  1.00000  1.00000    20  a 
    # f3() 18.35381 18.42019 18.30015 18.35580 18.20973 18.21109    20   b
    

提交回复
热议问题