Using pattern matching in R, how can I find if there are more than one matches per character string?

Viewed 83

I have the following vector:

vector1 <- c("Frank frank", "Frank", "Fred", "frank")

I wish to determine how many times the word 'Frank' or 'frank' appear in the vector. I want to count individual occurrences and keep track of how many times this pattern appears in each character string within the vector.

The result should look like this:

2 1 0 1

Thanks!

3 Answers

We can use str_count, wrap the pattern in modifiers e.g. regex and make use of the additional arguments i.e. ignore_case which is by default FALSE

library(stringr)
str_count(vector1, regex('Frank', ignore_case = TRUE))
[1] 2 1 0 1

Or using base R, extract the words into a list and then count the the lengths of the list i.e. length of each list element

lengths(regmatches(vector1, gregexpr("[Ff]rank", vector1)))
[1] 2 1 0 1

Combining gregexpr and regmatches can be one base-r approach

v = c("Frank frank", "Frank", "Fred", "frank")
res = regmatches(v, gregexpr('frank', v, ignore.case = T))
res 
[[1]]
[1] "Frank" "frank"

[[2]]
[1] "Frank"

[[3]]
character(0)

[[4]]
[1] "frank"

lengths(res)

[1] 2 1 0 1

You can also collapse the two versions of "Frank" or use a general regex:

library(stringr)

str_count(vector1, "[fF]rank")

OR

str_count(vector1, "Frank|frank")

[1] 2 1 0 1
Related