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 se
The with
function will let you use shorthand column references and sum
will count TRUE
results from the expression(s).
sum(with(aaa, sex==1 & group1==2))
## [1] 3
sum(with(aaa, sex==1 & group2=="A"))
## [1] 2
As @mnel pointed out, you can also do:
nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3
nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2
The benefit of that is that you can do:
nrow(aaa)
## [1] 6
And, the behaviour matches Stata's count
almost exactly (syntax notwithstanding).