使用 mtcars 数据集,我想计算该数据集中有多少辆汽车至少有 6 个气缸 (cyl)。
我在过滤后使用length(),得到的结果是11
library(dplyr)
mtcars %>%
filter(
cyl > 6
) %>%
length()
然而教程提供的代码是这样的,返回结果为14
library(dplyr)
mtcars %>%
filter(cyl > 6) %>%
summarise(n())
过滤后直接查看结果,应该也是14
现在我了解到 summarise(n()) 更好 使用 dplyr 按组计算行数,并且有更多更好的方法在过滤后进行计数,但我仍然很困惑为什么我的代码返回不同的结果以及11 来自。
谢谢
应用于数据框时,
length()
返回列数而不是行数。但您可以 pull
变量来查看它们的 lenghth
。因此,您的代码计算的是列数而不是行数。
library(dplyr)
# Counts columns
mtcars %>%
filter(
cyl > 6
) %>%
length()
#> [1] 11
# Counts rows
mtcars %>%
filter(cyl > 6) %>%
summarise(n())
#> n()
#> 1 14
# Counts rows
mtcars %>%
filter(
cyl > 6
) %>%
pull() %>%
length()
#> [1] 14
创建于 2024-05-12,使用 reprex v2.1.0