Skip to main content

Section 2.6 Insights Into Our Data

We have done a fantastic job of manipulating our data. But, what if we want a different set of insights? What if, for example, we want to uncover summarized data relating to the three different species in our penguins dataset?

Subsection 2.6.1 Count

Before, we utilized the nrow() function to find out how many rows there are overall in the penguins dataset. We also utilized the distinct() command to find out how many different species there are in the penguins dataset. But, as of right now, we currently do not know how many rows each species has. Using base R, we can use the table() command, and in the tidyverse, we can use the count() command.
table(penguins$species)
Adelie Chinstrap    Gentoo 
      152        68       124
penguins |> count(species, sort = TRUE)
# A tibble: 3 Γ— 2
  species       n
  <fct>     <int>
1 Adelie      152
2 Gentoo      124
3 Chinstrap    68
We now have exactly what we wanted - the number of rows in the dataset for each species. This is great for finding counts, but there may be cases where we need more summarized data than just counts.

Subsection 2.6.2 Summarizing and Grouping

In cases like this (similar to a pivot table in Excel), we can utilize both the group_by() and the summarize() commands in R. The first tells R which column you want to group by, and the second tells it what data you want summarized.
Below, we will be finding out the total number of rows in the dataset per species and the mean body mass of each species.
penguins |>
  group_by(species) |>
  summarize(
    n         = n(),
    mean_mass = mean(body_mass_g, na.rm = TRUE))
# A tibble: 3 Γ— 3
  species       n mean_mass
  <fct>     <int>     <dbl>
1 Adelie      152     3701.
2 Chinstrap    68     3733.
3 Gentoo      124     5076.
VoilΓ ! This table has summarized data per each of the three species of penguins. Notice that here we used the n() command instead of count() as it works better with summarize(), but gets the same results.
In later chapters, these same tidyverse tools will be used to prepare data for visualization, statistical modeling, and interpretation.