# R 中的觀測值計數

Manav Narula 2021年2月25日

``````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
``````

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.