pyll
pyll

Reputation: 1764

Return number of rows from dplyr filter

I am looking for a simple piece of code to report the number of rows returned from a filter. Using the iris dataset,

iris %>%
  filter(Species == 'setosa',
         Sepal.Length >= 5.7) 

Three rows are returned by this statement, so I would like the output to just read '3' in the console. Better yet, I would ultimately like to name this object 'Answer1'.

Upvotes: 3

Views: 4282

Answers (2)

superboreen
superboreen

Reputation: 57

iris %>%
    filter(Species == 'setosa', Sepal.Length >= 5.7) %>%
    count()

Upvotes: -2

Frank
Frank

Reputation: 66819

The tally function counts rows meeting a condition and returns a data.frame with the count in column n:

iris %>% tally(Species == 'setosa' & Sepal.Length >= 5.7)

  n
1 3

If you want the number alone, I guess the currently idiomatic way might be:

library(purrr)
iris %>% tally(Species == 'setosa' & Sepal.Length >= 5.7) %>% pluck("n")

[1] 3

Or if you like filter, just pipe to nrow:

iris %>% filter(Species == 'setosa', Sepal.Length >= 5.7) %>% nrow

[1] 3

Upvotes: 4

Related Questions