Reputation: 920
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
Reputation: 887721
Or an option with table
after removing the substring at the end
table(sub("_.*", "", vec1))
# apple orange
# 3 2
Upvotes: 2
Reputation: 32558
sapply(c("apple", "orange"), function(x) sum(grepl(x, vec1)))
# apple orange
# 3 2
Upvotes: 4