Okay, let's tell a story about a classic built-in R dataset: the iris dataset. This dataset contains measurements of iris flowers from three different species.
The story will flow like this:
- Introduction: What is this data about? How many observations and variables?
- Overall Look: What do the measurements look like across all flowers?
- Meet the Characters: How are the flowers divided? (By Species).
- Group Profiles: How do the measurements differ between the species?
- Visual Storytelling: Show the differences with plots.
- Summary: What have we learned?
We'll use base R, dplyr for data manipulation (making summaries easier and more readable), and ggplot2 for plotting.
# --- Required Libraries ---
# If you don't have these, install them using:
# install.packages("dplyr")
# install.packages("ggplot2")
library(dplyr)
library(ggplot2)
# --- Load the Dataset ---
# The iris dataset is built into R, so no need to load from a file.
data(iris)
# --- Start the Story ---
print("--- Telling the Story of the Iris Dataset ---")
print("") # Add a blank line for readability
# --- 1. Introduction: What is this data? ---
print("Part 1: Getting to Know the Data")
print("---------------------------------")
print("The 'iris' dataset contains measurements of 150 iris flowers.")
print("There are four measured variables (in centimeters):")
print(" - Sepal.Length")
print(" - Sepal.Width")
print(" - Petal.Length")
print(" - Petal.Width")
print("And one categorical variable:")
print(" - Species (setosa, versicolor, or virginica)")
# Display the first few rows to see what it looks like
print("\nFirst 5 rows:")
print(head(iris))
# Display the structure of the dataset
print("\nStructure of the dataset:")
print(str(iris))
# Display the dimensions
print(paste("\nNumber of observations (flowers):", nrow(iris)))
print(paste("Number of variables:", ncol(iris)))
print("\n---------------------------------\n") # Separator
# --- 2. Overall Look: Summary Statistics ---
print("Part 2: Looking at the Big Picture (Overall Measurements)")
print("-------------------------------------------------------")
print("Let's see the general range and typical values for the measurements across ALL flowers.")
# Using the base R summary function
print(summary(iris))
print("\nKey observations from the overall summary:")
print("- Sepal Length ranges from 4.3 cm to 7.9 cm.")
print("- Sepal Width ranges from 2.0 cm to 4.4 cm.")
print("- Petal Length ranges from 1.0 cm to 6.9 cm. Notice the very low minimum compared to others.")
print("- Petal Width ranges from 0.1 cm to 2.5 cm. Also a very low minimum.")
print("\n-------------------------------------------------------\n") # Separator
# --- 3. Meet the Characters: Exploring the Species ---
print("Part 3: Introducing the Species")
print("-------------------------------")
print("The dataset groups flowers by species. Let's see how many of each species we have.")
# Using base R table function
print("\nCounts by Species:")
print(table(iris$Species))
# Or using dplyr
# iris %>% count(Species) %>% print()
print("\nIt seems we have an equal number of observations (50) for each of the three species.")
print("\n-------------------------------\n") # Separator
# --- 4. Group Profiles: Summary Statistics by Species ---
print("Part 4: How Do the Measurements Differ by Species?")
print("--------------------------------------------------")
print("This is where the story gets interesting. Let's calculate the summary statistics for each species separately.")
# Using dplyr for a clear group-by-summarize operation
summary_by_species <- iris %>%
group_by(Species) %>%
summarise(
n = n(), # Number of flowers in this group
Avg_Sepal_Length = mean(Sepal.Length),
SD_Sepal_Length = sd(Sepal.Length),
Avg_Sepal_Width = mean(Sepal.Width),
SD_Sepal_Width = sd(Sepal.Width),
Avg_Petal_Length = mean(Petal.Length),
SD_Petal_Length = sd(Petal.Length),
Avg_Petal_Width = mean(Petal.Width),
SD_Petal_Width = sd(Petal.Width),
Min_Petal_Length = min(Petal.Length), # Adding min/max for key variables
Max_Petal_Length = max(Petal.Length),
Min_Petal_Width = min(Petal.Width),
Max_Petal_Width = max(Petal.Width)
)
print("Summary statistics for each species:")
print(summary_by_species)
print("\nKey observations from the species summary:")
print("- **setosa**: Has the smallest average Sepal Length, but the largest average Sepal Width. Crucially, it has *much* smaller average Petal Length and Petal Width than the others. The min/max petal dimensions confirm this distinct separation.")
print("- **versicolor**: Appears to be intermediate in most measurements.")
print("- **virginica**: Generally has the largest Sepal Length, Petal Length, and Petal Width on average.")
print("\n--------------------------------------------------\n") # Separator
# --- 5. Visual Storytelling: Showing the Differences ---
print("Part 5: Visualizing the Story")
print("-----------------------------")
print("Numbers are great, but plots can show the story much more clearly.")
print("Let's plot the relationships and differences, coloring by species.")
# Scatter plot of Petal Length vs. Petal Width, colored by species
# This is often the most striking plot for this dataset
plot_petal <- ggplot(iris, aes(x = Petal.Length, y = Petal.Width, color = Species)) +
geom_point(alpha = 0.8, size = 3) + # Use geom_point for scatter plot
labs(title = "Petal Length vs. Petal Width by Species",
x = "Petal Length (cm)",
y = "Petal Width (cm)",
color = "Species") +
theme_minimal() + # Clean theme
theme(legend.position = "bottom") # Position legend nicely
print("Plot 1: Petal Length vs. Petal Width by Species")
print(plot_petal)
# Scatter plot of Sepal Length vs. Sepal Width, colored by species
plot_sepal <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_point(alpha = 0.8, size = 3) +
labs(title = "Sepal Length vs. Sepal Width by Species",
x = "Sepal Length (cm)",
y = "Sepal Width (cm)",
color = "Species") +
theme_minimal() +
theme(legend.position = "bottom")
print("\nPlot 2: Sepal Length vs. Sepal Width by Species")
print(plot_sepal)
# Boxplot for Petal Length by Species to show distributions
plot_petal_length_boxplot <- ggplot(iris, aes(x = Species, y = Petal.Length, fill = Species)) +
geom_boxplot() + # Use geom_boxplot
labs(title = "Petal Length Distribution by Species",
x = "Species",
y = "Petal Length (cm)") +
theme_minimal() +
theme(legend.position = "none") # Hide legend as x-axis labels are sufficient
print("\nPlot 3: Petal Length Distribution by Species (Boxplot)")
print(plot_petal_length_boxplot)
# Boxplot for Petal Width by Species
plot_petal_width_boxplot <- ggplot(iris, aes(x = Species, y = Petal.Width, fill = Species)) +
geom_boxplot() +
labs(title = "Petal Width Distribution by Species",
x = "Species",
y = "Petal Width (cm)") +
theme_minimal() +
theme(legend.position = "none")
print("\nPlot 4: Petal Width Distribution by Species (Boxplot)")
print(plot_petal_width_boxplot)
print("\n-----------------------------\n") # Separator
# --- 6. Summary: What Did We Learn? ---
print("Part 6: The Story's Conclusion")
print("------------------------------")
print("Based on our exploration:")
print("- The dataset is well-structured with equal representation for each of the three iris species.")
print("- Overall summaries give us a general sense of the measurement ranges.")
print("- However, looking at the species individually reveals distinct patterns.")
print("- The **setosa** species is clearly separated from the others, characterized by significantly smaller petal dimensions and a relatively wider sepal.")
print("- **versicolor** and **virginica** have more overlap, especially in sepal dimensions, but are quite distinct when looking at petal dimensions.")
print("- **Petal Length** and **Petal Width** are the most discriminative features for distinguishing between these three iris species, allowing for almost perfect separation in a 2D plot.")
print("\n--- End of Story ---")
Explanation of the Code and Storytelling:
- Setup: Load
dplyr (for data manipulation) and ggplot2 (for plotting). These are standard and powerful packages.
- Load Data: The
iris dataset is built-in, so data(iris) makes it available.
- Introduction (
Part 1): Start by explaining what the dataset is. head() shows the raw data, str() shows variable types, nrow() and ncol() give dimensions.
- Overall Look (
Part 2): summary(iris) provides a quick overview of all columns, giving min, max, median, mean, quartiles for numeric data, and counts for factors. This gives a baseline before looking at groups.
- Meet the Characters (
Part 3): Use table(iris$Species) (or count() from dplyr) to see the distribution of the main categorical variable. This is important to know if the groups are balanced.
- Group Profiles (
Part 4): This is a key step. dplyr's group_by(Species) followed by summarise(...) calculates metrics (mean, std. deviation, min, max) for each species separately. Comparing these numbers directly reveals differences.
- Visual Storytelling (
Part 5): Plots are crucial for seeing patterns the numbers might hide.
ggplot() is used to create plots. aes() maps data variables to visual properties (x-axis, y-axis, color, fill).
geom_point() creates scatter plots. Coloring points by Species immediately shows how the groups separate.
geom_boxplot() creates boxplots, which are excellent for comparing the distribution of a variable across different categories (species).
labs() sets titles and axis labels for clarity.
theme_minimal() provides a clean look.
print() displays the plots.
- Summary (
Part 6): Conclude by summarizing the main findings based on both the numerical summaries and the visualizations. Highlight the most important insights (e.g., Setosa is distinct, petal dimensions are key discriminators).
This code is precise because it uses correct R functions for specific tasks (summarizing, grouping, plotting). It's readable because it uses clear variable names, comments, adds descriptive text using print(), and breaks down the analysis into logical, numbered sections. The "story" aspect comes from the narrative flow (Intro -> Overall -> Groups -> Differences -> Visuals -> Conclusion) and the interpretation provided alongside the code output.