summarize() function with the n() and count() arguments

Hey everyone, beginner to R. Just wondering, why doesn't the count() function work as an argument in the summarize() function, but n() does? Isn't the entire point of count to count? It kind of threw me off.

Example with count():

starwars %>%
drop_na(gender) %>%
group_by(gender) %>%
summarize(how_many_genders= count())

Result:

Error

Example with n():

starwars %>%
drop_na(gender) %>%
group_by(gender) %>%
summarize(how_many_genders= n())

Result:

Screenshot 2024-05-26 at 7.23.49 PM

count() returns a dataframe, which isn't what you want inside summarize().

2 Likes

Thank you! I didn't know count's purpose was to return data frames and that it was actually n() function to count rows. Could you show an example with the count function?

Take a look at the help file with ?count. But here's a very simple example.

>library(tidyverse)
> t <- tibble(variable = 1:10)
> count(t)
# A tibble: 1 × 1
      n
  <int>
1    10
1 Like

The function count() is NOT used within summarize. I think what you want is this:

library(tidyverse)

starwars %>%
  drop_na(gender) %>%
  count(gender, name="how_many_genders")
#> # A tibble: 2 × 2
#>   gender    how_many_genders
#>   <chr>                <int>
#> 1 feminine                17
#> 2 masculine               66

starwars %>%
  drop_na(gender) %>%
  group_by(gender) %>%
  summarize(how_many_genders= n())
#> # A tibble: 2 × 2
#>   gender    how_many_genders
#>   <chr>                <int>
#> 1 feminine                17
#> 2 masculine               66

Created on 2024-05-28 with reprex v2.1.0

3 Likes