Navid Forootan
Navid Forootan

Reputation: 3

Count the number of hyphens in a name using R

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

Answers (2)

Ronak Shah
Ronak Shah

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

akrun
akrun

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

Related Questions