How to count the number of observations in R like Stata command count
Asked Answered
K

2

11
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 specified conditions. If no conditions are specified, count displays the number of observations in the data.

How to count in R? Thank you.

Knitwear answered 18/5, 2014 at 22:54 Comment(1)
Here is a reasonable dictionary mapping stata commands to rAulos
L
14

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).

Lolanthe answered 18/5, 2014 at 22:59 Comment(0)
D
4

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

> library(dplyr)

> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2
Dispeople answered 9/4, 2017 at 19:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.