How to count the number of observations in R, like the count of the Stata count command

aaa<- data.frame(sex=c(1,1,2,2,1,1), group1=c(1,2,1,2,2,2),group2=c("A","B","A","B","A","B")) 

Stata command:

 count if sex==1 & group1==2 count if sex==1 & group2=="A" 

count counts the number of observations that satisfy the given conditions. If no conditions are specified, the counter displays the number of observations in the data.

How to count in R? Thanks.

+7
r stata
source share
2 answers

The with function allows you to use abbreviated column references, and sum will consider TRUE result of the expression (s).

 sum(with(aaa, sex==1 & group1==2)) ## [1] 3 sum(with(aaa, sex==1 & group2=="A")) ## [1] 2 

As @ mnel noted, you can also:

 nrow(aaa[aaa$sex==1 & aaa$group1==2,]) ## [1] 3 nrow(aaa[aaa$sex==1 & aaa$group2=="A",]) ## [1] 2 

The advantage is that you can:

 nrow(aaa) ## [1] 6 

And the behavior matches the Stata count almost exactly (despite the syntax).

+9
source share

You can also use the filter function from the dplyr package, which returns strings with matching conditions.

 > library(dplyr) > nrow(filter(aaa, sex == 1 & group1 == 2)) [1] 3 > nrow(filter(aaa, sex == 1 & group2 == "A")) [1] 2 
0
source share

All Articles