count the number of plus signs in a character string

Goal

count the number of plus signs in the following model (character string) using base R

y ~ z + x1 + x2 + x3 + x4 + x5 + x6 + x8 + x9 + x10 + x11  

Source code

model <- as.formula("y~z+x1+x2+x3+x4+x5+x6+x8+x9+x10+x11")
model

me <- gsub("y ~ ", "", model)
me
me2 <- length(unlist(gregexpr('+', me)))
me2

Output

y ~ z + x1 + x2 + x3 + x4 + x5 + x6 + x8 + x9 + x10 + x11    
[1] "~"                                                    
[2] "y"                                                    
[3] "z + x1 + x2 + x3 + x4 + x5 + x6 + x8 + x9 + x10 + x11"
[1] 55     why does this not equal 11?

Because it does not equal 10

model <- as.formula("y~z+x1+x2+x3+x4+x5+x6+x8+x9+x10+x11")
me <- gsub("y ~ ", "", model)
length(grep(" ",gsub("[a-z~0-9]"," ",unlist(strsplit(me," "))),invert = TRUE, value = TRUE))
#> [1] 10

Created on 2023-03-13 with reprex v2.0.2

I would do it like so :

library(stringr) # or library(tidyverse)
(model <- as.formula("y~z+x1+x2+x3+x4+x5+x6+x8+x9+x10+x11"))
(me <- toString(model))
(me2 <- str_count(me,fixed("+")))

Thanks. I forgot x7 was not in this model. This is why I need this hard coded.

I like the simplicity of stringr code. Thanks.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.