Of course. Here is a piece of R code that tells a story using the palmerpenguins dataset. The code is structured like a narrative, with comments explaining each step of our investigation. It's designed to be run top-to-bottom in an environment like RStudio.
The story is about a researcher who discovers a new set of penguin data and sets out to understand the differences between the species.
The Story of the Palmer Penguins: A Data Detective's Journal
# Title: The Story of the Palmer Penguins
# Author: A Data Detective
# Date: Today
#
# Synopsis: We receive a new dataset on penguins from the Palmer Archipelago.
# Our mission is to explore this data to understand the key characteristics
# that distinguish the three penguin species: Adelie, Chinstrap, and Gentoo.
# -- ACT I: Meeting the Characters --
# Every good story needs a setting and a cast. Let's load the tools and
# data we need to begin our investigation.
# First, we need our detective's toolkit (the R packages).
# The 'tidyverse' is for data manipulation and visualization (our magnifying glass).
# The 'palmerpenguins' package contains the data itself.
# The 'rpart' packages will help us build a predictive model (our theory).
# If you don't have them, uncomment the following lines to install:
# install.packages("tidyverse")
# install.packages("palmerpenguins")
# install.packages("rpart")
# install.packages("rpart.plot")
library(tidyverse)
library(palmerpenguins)
library(rpart)
library(rpart.plot)
# Now, let's meet the subjects of our investigation.
# We'll load the data and take a look at the first few entries.
penguins_raw <- palmerpenguins::penguins
cat("--- Our Case File: A First Look at the Penguin Data ---\n")
print(head(penguins_raw))
# Our initial inspection reveals several clues (columns): species, island,
# bill measurements, flipper length, body mass, and sex.
#
# We also spot some missing values (`NA`), which are like smudges on our
# case file. For a clean investigation, we'll work with the complete records.
penguins <- penguins_raw %>%
na.omit()
cat("\n--- After cleaning the file (removing NAs), we have", nrow(penguins), "complete records. ---\n")
# -- ACT II: The Investigation Begins --
# Our first question: Where do these penguins live, and do they live together?
# Let's create a census of penguins on each island.
cat("\n--- Clue #1: The Distribution of Species by Island ---\n")
island_census_plot <- ggplot(penguins, aes(x = species, fill = species)) +
geom_bar(show.legend = FALSE) +
facet_wrap(~island) +
labs(
title = "Penguin Population by Island",
subtitle = "Adelies are widespread, but Gentoos and Chinstraps stick to their own islands.",
x = "Penguin Species",
y = "Count"
) +
theme_minimal()
print(island_census_plot)
# The plot reveals something interesting! Adelies are found on all three islands.
# However, Gentoos live only on Biscoe, and Chinstraps live only on Dream.
# This is a strong clue, but what if we find a penguin and don't know its island?
# We need to find physical traits that can identify them anywhere.
# -- ACT III: The 'Aha!' Moment --
# Let's investigate the physical measurements. Are there tell-tale signs
# that distinguish the species? We suspect bill shape might be a key differentiator.
# Let's plot bill length against bill depth.
cat("\n--- The 'Aha!' Moment: Uncovering the Secret in Their Bills ---\n")
bill_relationship_plot <- ggplot(penguins, aes(x = bill_length_mm, y = bill_depth_mm)) +
geom_point(aes(color = species, shape = species, size = body_mass_g), alpha = 0.8) +
scale_color_manual(values = c("Adelie" = "#ff8c00", "Chinstrap" = "#9400d3", "Gentoo" = "#008b8b")) +
labs(
title = "The Telltale Difference: Bill Shape Separates the Species",
subtitle = "Gentoos have long, shallow bills. Chinstraps have long, deep bills. Adelies have short, deep bills.",
x = "Bill Length (mm)",
y = "Bill Depth (mm)",
color = "Species",
shape = "Species",
size = "Body Mass (g)"
) +
theme_minimal() +
guides(size = "none") # Hiding the size legend for clarity
print(bill_relationship_plot)
# This is it! The breakthrough!
# The plot shows three distinct clusters. By just looking at the length and
# depth of a penguin's bill, we can make a very educated guess about its species.
#
# - Adelies: Short bills, medium-to-high depth.
# - Gentoos: Long bills, but very shallow depth.
# - Chinstraps: Long bills and high depth.
# It seems the Gentoos are also noticeably heavier (larger circles), giving us another clue.
# -- ACT IV: Building the Theory --
# We've solved the case visually, but can we create a precise set of rules?
# Let's build a simple decision tree model. This is like teaching a rookie detective
# the rules we just discovered. We'll use bill and flipper measurements to predict the species.
cat("\n--- Formalizing Our Theory: A Decision Tree ---\n")
# The formula reads: "Predict the species based on these measurements."
penguin_formula <- species ~ bill_length_mm + bill_depth_mm + flipper_length_mm
# Now, we train our model on the data.
penguin_tree <- rpart(penguin_formula, data = penguins, method = "class")
cat("The model has learned the following rules to identify penguins:\n")
# Let's visualize the rules our model has learned.
rpart.plot(penguin_tree,
box.palette = "auto", # Use a nice color palette
main = "A Detective's Guide to Identifying Palmer Penguins",
tweak = 1.2 # Adjust text size
)
# -- FINALE: The Case is Closed --
# The decision tree provides a crystal-clear summary of our findings.
# For example, it learned that if a penguin's bill depth is less than 15.5mm,
# it's almost certainly a Gentoo. If not, it checks the bill length to
# separate the Adelies from the Chinstraps.
#
# Our journey is complete. We started with a mysterious dataset and,
# through careful exploration and visualization, uncovered the simple yet
# elegant physical traits that define each penguin species.
#
# The story of the Palmer Penguins is a story of diversity, written in the
# language of data. Case closed.
cat("\n--- The End ---\n")