'Count number of rows that fulfill multiple conditions in R

I have a dataframe:

df <- data.frame (ID  = c(1:20),
                  Ethnicity = c(rep(c("White", "Asian", "Black", "Hispanic", "Other"), times=20/5)),
                  Age = c(1:20),
                  Set = rep(c(1,2,3,4), times=20/4)
)

What is the most efficient way to count the number of rows that have Ethnicity== 'Asian' and Set == 3?

Thanks!



Solution 1:[1]

Depends on what you're measure of efficiency is but

sum(df$Ethnicity== 'Asian' & df$Set == 3)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marcus