简体   繁体   English

如何计算R中的观察数量,如Stata命令计数

[英]How to count the number of observations in R like Stata command count

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: stata命令:

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

count counts the number of observations that satisfy the specified conditions. count计算满足指定条件的观察数。 If no conditions are specified, count displays the number of observations in the data. 如果未指定条件,count将显示数据中的观察数。

How to count in R? 怎么算R? Thank you. 谢谢。

The with function will let you use shorthand column references and sum will count TRUE results from the expression(s). with函数将允许您使用速记列引用, sum将从表达式计算TRUE结果。

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: 正如@ mnel指出的那样,你也可以这样做:

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). 并且,该行为几乎完全匹配Stata的count (尽管语法)。

You can also use the filter function from the dplyr package which returns rows with matching conditions. 您还可以使用dplyr包中的过滤器函数,该函数返回具有匹配条件的行。

> library(dplyr)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM