Reputation: 3
I have a data set with a certain amount of names. How can I count the number of names with at least one hyphen using R?
Upvotes: 0
Views: 304
Reputation: 389012
In base R, we can use grepl
sum(grepl('-', df$Name))
Or with grep
length(grep('-', df$Name))
Using a reproducble example,
df <- data.frame(Name = c('name1-name2', 'name1name2',
'name1-name2-name3', 'name2name3'))
sum(grepl('-', df$Name))
#[1] 2
length(grep('-', df$Name))
#[1] 2
Upvotes: 2
Reputation: 887213
We can use str_count
to get the number of hyphens and then count by creating a logical vector and get the sum
library(stringr)
sum(str_count(v1, "-") > 0)
Upvotes: 4