How to count the occurrences of a specific value in a single column in R

Viewed 811

I have a df such as

a     b     sex
yes  yes    male
no   yes    female
yes  no     male

I would like to count and store as an object only the count of males in the sex column.

I am running this:

n_male <- length(grep('male', tbl1_df[ ,"sex"]))
n_male

Because 'male' is in 'female', however, I am getting n_male = 3. How can I change this function to make it n_male = 2?

3 Answers

Based on the example showed, there is no need for substring matching. We can directly use fixed match with == and get the count with sum of logical vector

n_male <- sum(tbl1_df$sex == 'male')
n_male
#[1] 2

With grep, it can also match substring. There is male in female.

If we want to use grep, specify a word boundary

n_male <- sum(grepl('\\bmale\\b', tbl1_df$sex))

Or with length/grep

n_male <- length(grep('\\bmale\\b', tbl1_df$sex))

Also, in base R, we can just use table

table(tbl1_df$sex)

to get the counts of both

If you could use the mosaic package, then you could do:

library(mosaic)
tally(~sex, data = tbl1_df)

sex
female   male 
     1      2 

count() lets you quickly count the unique values of one or more variables: df %>% count(a, b)

library(dplyr)
df %>% count(sex)
Related