count the number of occurrences of “(” in a string

后端 未结 3 652
别跟我提以往
别跟我提以往 2020-12-11 15:33

I am trying to get the number of open brackets in a character string in R. I am using the str_count function from the stringr package



        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 15:53

    You could also use gregexpr along with length in base R:

    sum(gregexpr("(", s, fixed=TRUE)[[1]] > 0)
    [1] 3
    

    gregexpr takes in a character vector and returns a list with the starting positions of each match. I added fixed=TRUE in order to match literals.length will not work because gregexpr returns -1 when a subexpression is not found.


    If you have a character vector of length greater than one, you would need to feed the result to sapply:

    # new example
    s<- c("(hi),(bye),(hi)", "this (that) other", "what")
    sapply((gregexpr("(", s, fixed=TRUE)), function(i) sum(i > 0))
    [1] 3 1 0
    

提交回复
热议问题