John legend2
John legend2

Reputation: 920

How to count values including a particular word?

I have a vector with characters and would like to count values including a certain word.

For instance, I have this

vec1 = c("apple_a1","apple_a2","apple_a3"  ,"orange_a1","orange_a2" )

With vec1, How can I count values having "apple", and "orange" separately?

So, my desired outcome is 3 for apple and 2 for orange.

Upvotes: 1

Views: 44

Answers (2)

akrun
akrun

Reputation: 887721

Or an option with table after removing the substring at the end

table(sub("_.*", "", vec1))
#  apple orange 
#    3      2 

Upvotes: 2

d.b
d.b

Reputation: 32558

sapply(c("apple", "orange"), function(x) sum(grepl(x, vec1)))
# apple orange 
#     3      2 

Upvotes: 4

Related Questions