我正在寻找一段简单的代码来报告从过滤器返回的行数。 使用iris
数据集,
iris %>%
filter(Species == 'setosa',
Sepal.Length >= 5.7)
此语句返回三行,因此我希望输出在控制台中仅读取"3"。 更好的是,我最终想将这个对象命名为"Answer1"。
tally
函数对满足条件的行进行计数,并返回一个 data.frame,其中计数在第n
列中:
iris %>% tally(Species == 'setosa' & Sepal.Length >= 5.7)
n
1 3
如果你只想要这个数字,我想目前的惯用方式可能是:
library(purrr)
iris %>% tally(Species == 'setosa' & Sepal.Length >= 5.7) %>% pluck("n")
[1] 3
或者如果你喜欢filter
,只需管道到nrow:
iris %>% filter(Species == 'setosa', Sepal.Length >= 5.7) %>% nrow
[1] 3
iris %>%
filter(Species == 'setosa', Sepal.Length >= 5.7) %>%
count()