# R 中的观测值计数

Manav Narula 2021年2月25日 2021年1月22日

``````df <- data.frame( gender = c("M","F","M","M"),
age = c(18,19,14,22),
stream = c("Arts","Science","Arts","Commerce"))
print(df)
``````

``````  gender age   stream
1      M  18     Arts
2      F  19  Science
3      M  14     Arts
4      M  22 Commerce
``````

`with()` 函数在应用于整个数据集后，根据某个表达式返回一个逻辑向量，而 `sum()` 函数将返回所有 `True` 观测值的总和。

``````df <- data.frame( gender = c("M","F","M","M"),
age = c(18,19,14,22),
stream = c("Arts","Science","Arts","Commerce"))

sum(with(df,gender == "M"))
[1] 3
``````

``````sum(with(df,gender == "M" & stream == "Commerce"))
[1] 1
``````

``````nrow(df[df\$gender == "M",])
[1] 3
``````

``````nrow(df[df\$gender == "M" & df\$stream == "Commerce",])
[1] 1
``````

``````library(dplyr)
nrow(filter(df,gender == "M"))
[1] 3
nrow(filter(df,gender == "M" & stream == "Commerce"))
[1] 1
``````
Author: Manav Narula

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.