Reputation: 23
I want to calculate the number of occurrences of a character in a string,
I've tried
length(grep("3", "987654332")[[1]])
[1] 1
It doesn't calculate the second occurrence of "3".
I also tried
length(gregexpr("0", "98765432")[[1]])
[1] 1
This calculate the multiple occurrences fine, but returns 1 for non occurring values.
Thank you!
Upvotes: 2
Views: 172
Reputation: 89067
Because gregexpr
returns -1
when there is no match, you can do:
> sum(gregexpr("3", "3398765432")[[1]] != -1)
[1] 3
> sum(gregexpr("0", "3398765432")[[1]] != -1)
[1] 0
Upvotes: 4