๐ช Day 2: Loops and Magic Libraries#
Oda the Data Otter learns to repeat magic spells and discovers Rโs treasure box of helpful tools!
๐ฏ Learning Objectives#
๐ Master for loops to repeat magical actions automatically
๐ Discover what open-source means and how packages work
๐ Learn how to get help using the
?function๐จ Create your first simple visualizations with ggplot2
๐๏ธ Understand what dataframes are with simple examples
1. Ice Breaker: Human Decision Tree Builder#
Duration: 15 minutes
๐ Activity: Work in groups of 3-4 to interview each other, draw a decision tree, and write if-else code that sorts each group member into a unique category! This refreshes Day 1โs if-else magic while preparing us for data exploration.
How to Play:
Discovery Questions (4 min): Share with your group:
What do you have in common with some (but not all) group members?
What makes you different from everyone else in your group?
Example discoveries:
โSarah loves math, but Sky and Jamie prefer artโ
โOnly Sky has a pet, the rest of us donโt have anyโ
โSky and Sarah are 12+, but Jamie is 11โ
Find Your Split Points (5 min):
What question divides your group into 2 roughly equal parts?
Within each part, what question separates people further?
Can you create a path where everyone ends up alone?
Draw & Code (5 min):
Simple Example Decision Tree:
Age >= 12?
/ \
YES NO
/ \
Love math? Jamie (11)
/ \ "Young Explorer"
YES NO
/ \
Sarah (12) Sky (28)
"Math Wizard" "Pet Lover"
Corresponding R Code:
# Test with each person's info!
name <- "Sarah" # Try "Sarah", "Sky", "Jamie"
age <- 12 # Sarah: 12, Sky: 13, Jamie: 11
loves_math <- TRUE # Sarah: TRUE, Sky: FALSE, Jamie: FALSE
has_pet <- FALSE # Sarah: FALSE, Sky: TRUE, Jamie: FALSE
if (age >= 12) {
if (loves_math == TRUE) {
print("Sarah: ๐งฎ Math Wizard!") # Sarah lands here
} else {
print("Sky: ๐ Pet Lover!") # Sky lands here
}
} else {
print("Jamie: ๐ Young Explorer!") # Jamie lands here
}
Reflect (1 min):
Does everyone get their own category?
What surprised you about your groupโs similarities and differences?
2. Magic Loops: Making R Repeat Spells#
Duration: 85 minutes
๐ญ Imagine youโre a chef baking 10 cookies. Instead of repeat the actions, โmix flour, add sugar, bakeโ, 10 separate times, you create a robot and repeat this procedure for you 10 times! Thatโs exactly what for loops do - they let us repeat code without typing it over and over.
๐ฎ The Magic Formula: for (number in 1:10) { # do something }
numberis like a counter that changes each time (number = 1, then 2, then 3โฆ)1:10means โcount from 1 to 10โEverything inside
{}get executed 10 times!
for (number in 1:10){
print(paste("๐ช Making Cookie #", number))
print("๐ฅ Mix flour")
print("๐ฏ Add sugar")
print("๐ฅ Bake")
print("") # add an empty line before we start making the next cookie!
}
2.1 Spell 1: Basic Loop Magic#
Duration: 15 minutes
๐ Find this spell in Posit Cloud: Look for the file day02_spell01_basic_loops.Rmd in your project files!
2.1.1 ๐ฎ R Markdown Files (.Rmd)#
๐ Big upgrade! Yesterday we used .R files, but today weโre using .Rmd files - theyโre like super-powered R files!
๐ก What is an R Markdown (.Rmd) file?#
Think of it like a magic notebook where you can mix your hand-written notes with code!
Day 1: We used
.Rfiles - just plain codeDay 2+: We use
.Rmdfiles - code + beautiful formatting + notes all in one!

๐ฏ Key Parts of .Rmd Files:#
1. Text/Paragraphs ๐
Click
insertโ>paragraphto add a new paragraph blockJust type normally like this sentence
Use
#for big titles,##for smaller titlesUse
**bold**or*italic*for emphasis
2. Code Chunks ๐ป
Click
insertโ>Executable Cellโ>Rto add a new paragraph blockCode lives inside special โfencesโ that look like this:
```{r}
print("This is R code!")
```
Click the โถ๏ธ green arrow to run just that chunk
You can run one piece at a time instead of the whole file!
3. Two Ways to View Your File:
๐
SourceMode: See the raw code and text (like peeking behind the magic curtain)๐๏ธ
VisualMode: See it formatted nicely (like the final magic show)Click the buttons at the top left to switch between them!
4. The Knit Button ๐งถ
Turns your .Rmd file into a beautiful HTML webpage or PDF file
Like magic - combines all your code, results, and explanation notes into one pretty document
Try it later to see your work as a professional report!
Letโs use .Rmd files to learn how to make R repeat actions automatically! Weโll start by printing messages and watching our counter change.
๐ Activity: Printing Practice#
# Without a loop (tiring!)
print("Hello, magical world!")
print("Hello, magical world!")
print("Hello, magical world!")
print("Hello, magical world!")
print("Hello, magical world!")
# ๐ Basic loop - repeat 5 times
for (i in 1:5) {
print("Hello, magical world!")
}
# ๐ฏ Challenge 1: Print your name 3 times using a for loop
# Fill in the blanks, replace the ... with the correct number or string
for (i in 1:...) {
print("My name is ...")
}
# See what 'i' actually does
for (i in 1:5) {
print(paste("This is loop number", i))
}
# ๐ฏ Challenge 2: Create a countdown from 10 to 1
# Hint: Use 10:1 instead of 1:10
# Note: paste() glues strings together
for (countdown in ...:...) {
print(paste("Countdown:", countdown))
}
print("๐ Blast off!")
# โจ Advanced Challenge: Print different animals on each loop
# Note: c() creates a collection of items
animals <- c("๐ถ dog", "๐ฑ cat", "๐ฐ rabbit", "๐ธ frog", "๐ฆ duck")
for (i in 1:5) {
print(paste("Animal", i, "is a", animals[i]))
}
๐ก Pro Tips from this spell:
Think of
ias a magical counter that changes each time!The loop runs once for each number in the range you give it
Use
c()to create collections of items like animals or namespaste()is great for gluing strings and numbers together
2.2 ๐โโ๏ธ Physical Activity: Human For Loop Theater#
Duration: 30 minutes
๐ญ Now that you understand loops, letโs BE the loops! Time to get creative and invent your own human loop performance!
๐ Activity: Design Your Own Loop Performance#
๐ Your Mission: Work in groups of 5-6 to create and perform an original human for loop! You can use the examples below for inspiration, but we want to see YOUR creative ideas!
๐ช Example Inspiration (but make it your own!):
๐ช Example #1: Cookie Factory Assembly Line
Setup: 3 people are stations, 2 person is the โcookie dough,โ 1 person is the loop counter
Loop Counter says: โStarting iteration 1!โ
Station 1: โMixing flour!โ (stirring motion)
Station 2: โAdding sugar!โ (sprinkling motion)
Station 3: โBaking cookie!โ (oven motion)
Cookie dough 1 walks through all 4 stations, then goes to back of line โ> cookie 1 ready!
Loop Counter says: โStarting iteration 2!โ and repeat โ> Cookie dough 2 ready!
After 2 cookies: Everyone shouts โCookie factory loop complete!โ
๐ฐ Example #2: Human Computer Instructions
Setup: 1 person is the โcode,โ 4-5 people are individual โcomputer action actorsโ
Code calls out: โFor i in 1 to 3, execute these actions in sequence:โ
Code calls out: โIteration 1! Sarah - jump like a rabbit! Tom - spin around! Lisa - clap 2 times! Mike - roar like a lion!โ
Each actor performs their specific action when called: Sarah hops, Tom spins, Lisa claps, Mike roars
Code calls out: โIteration 2! Sarah - jump like a rabbit! Tom - spin around! Lisa - clap 2 times! Mike - roar like a lion!โ
Same actors repeat their same actions in the same order
Code calls out: โIteration 3! Sarah - jump like a rabbit! Tom - spin around! Lisa - clap 2 times! Mike - roar like a lion!โ
After iteration 3: Code says โLoop complete!โ and all actors freeze
๐จ Creative Ideas to Spark Your Imagination:
Sports training routines (jumping jacks, running laps, passing balls)
Morning routines (brush teeth, eat breakfast, get dressed)
Art creation (draw, color, cut, paste)
Music performances (clap, stomp, sing, repeat)
โฐ Timeline:
Planning & Practice (20 minutes): Brainstorm your loop idea, assign roles, and rehearse
Performances (10 minutes): Each group performs for 1-2 minutes
๐ Performance Guidelines:
Start by announcing: โOur loop is in iteration X!โ
End with: โLoop complete!โ or something creative
2.3 Spell 2: Loop Detective Challenge#
Duration: 15 minutes
๐ Find this spell in Posit Cloud: Look for the file day02_spell02_loop_debugging.Rmd in your project files!
๐ Activity: Fix the Broken Code#
๐ต๏ธ Detective Mission: Someone cast incomplete loop spells! Your job is to debug the broken code and fill in the blanks to make loops work perfectly. Follow the clues and fix the missing pieces!
# ๐ Broken Spell #1: Missing loop variable
# Goal: print numbers 1 through 7
for ( in 1:7) {
print(paste("Number:", i))
}
# ๐ Broken Spell #2: Missing closing brace
# Goal: print "Magic spell" 4 times
for (spell in 1:4) {
print("Magic spell")
# ๐ Broken Spell #3: Wrong range
# Goal: count from 1 to 10
for (num in 1:) {
print(paste("Counting:", num))
}
# ๐ Broken Spell #4: Missing quotes
# Goal: print a message with each student's name
students <- c("Alex", "Sam", "Jordan", "Taylor")
for (student in students) {
print(paste(Hello, student))
}
# ๐ Broken Spell #5: Incomplete calculation
# Goal: print the square of each number
for (number in 1:5) {
square <- number *
print(paste(number, "squared is", square))
}
# โจ Advanced Detective Challenge:
# Target pattern: โญ, โญโญ, โญโญโญ, โญโญโญโญ
for (i in 1:4) {
stars <-
for (j in 1:) {
stars <- paste(stars, "โญ", sep="")
}
print(stars)
}
2.4 Spell 3: Art with Loops#
Duration: 20 minutes
๐ Find this spell in Posit Cloud: Look for the file day02_spell03_art_with_loops.Rmd in your project files!
๐ Activity: Creative Programming Patterns#
โจ Challenge: Create beautiful art using loops and programming patterns - from simple stars to colorful grids and even Christmas trees!
# ๐จ Art Example 1: Simple patterns with basic symbols
print("--- Simple Hash Pattern ---")
for (row in 1:5) {
pattern <- ""
for (col in 1:row) {
pattern <- paste(pattern, "#", sep="")
}
print(pattern)
}
# ๐ Fish Pattern Example: Create a fish shape using # symbols
print("\n--- Fish Pattern ---")
fish_pattern <- c(
" ##",
" ##@#",
" ######",
" #------#",
"##########",
" ########",
" ######",
" ####",
" ##",
" ####",
" ######"
)
for (line in fish_pattern) {
print(line)
}
# ๐จ Art Example 2: Emoji patterns
print("\n--- Simple Star Pattern ---")
for (row in 1:5) {
stars <- ""
for (col in 1:row) {
stars <- paste(stars, "โญ", sep="")
}
print(stars)
}
# ๐จ Art Example 3: Colorful symbol patterns
print("\n--- Rainbow Pattern ---")
symbols <- c("๐ด", "๐ ", "๐ก", "๐ข", "๐ต", "๐ฃ")
for (row in 1:6) {
line <- ""
for (col in 1:row) {
symbol_index <- col %% 6 + 1
line <- paste(line, symbols[symbol_index], sep="")
}
print(line)
}
# ๐จ Art Example 4: Grid patterns
print("\n--- Grid Art ---")
symbols <- c("โญ", "๐", "โ๏ธ", "๐ซ")
for (row in 1:4) {
line <- ""
for (col in 1:6) {
symbol_index <- (row + col) %% 4 + 1
line <- paste(line, symbols[symbol_index], sep="")
}
print(line)
}
# ๐จ Art Example 5: Christmas tree pattern
print("\n--- Christmas Tree Pattern ---")
for (row in 1:5) {
# Add spaces for centering
spaces <- ""
for (space in 1:(5-row)) {
spaces <- paste(spaces, " ", sep="")
}
# Add stars for the tree
stars <- ""
for (star in 1:(2*row-1)) {
stars <- paste(stars, "๐", sep="")
}
# Print the complete line
print(paste(spaces, stars, sep=""))
}
# Add the tree trunk
print(" ๐ชต")
# ๐จ Art Example 6: Number triangle
print("\n--- Number Triangle ---")
for (row in 1:5) {
line <- ""
for (col in 1:row) {
if (col == 1) {
line <- paste(line, col, sep="")
} else {
line <- paste(line, col, sep=" ")
}
}
print(line)
}
# โจ YOUR TURN: Create your own artistic pattern
print("\n--- Your Creative Pattern ---")
# for (row in 1:...) {
# ...
# }
2.5 ๐คฏ Challenging Magic โ Spell 4: Story Scrambler Challenge (Optional)#
Duration: 20 minutes (excluded from time in chapter 2)
๐ Find this spell in Posit Cloud: Look for the file day02_spell04_story_scrambler.Rmd in your project files!
๐ The Magic Story: โIn the Magic Forest, a smart rabbit and a tiny dragon became friends, built a flying boat out of leaves, and sailed through the sky to save a sleepy bear cub who was stuck on a candy cloud.โ
๐ Activity: Secret Message Encoder & Decoder#
๐ต๏ธ Turn yourself into a data spy! Learn two secret encoding methods:
Method 1: Reverse word order (like reading backwards to confuse enemies!)
Method 2: Every-other-word scramble (mix odd and even positioned words!)
Create secret codes to share with friends using mini messages like โMeet me at the playground after schoolโ or โThe password is rainbow unicorn.โ
# ๐ The Magic Story to scramble
original_story <- "In the Magic Forest, a smart rabbit and a tiny dragon became friends, built a flying boat out of leaves, and sailed through the sky to save a sleepy bear cub who was stuck on a candy cloud."
# Split the story into individual words
# Note: unlist(strsplit()) splits a string into a list of words
story_words <- unlist(strsplit(original_story, " "))
print("๐ค Original story words:")
print(story_words)
print(paste("๐ Total words:", length(story_words)))
# ๐ฏ Challenge 1: Reverse Word Order Spy Code
print("\n๐ === CHALLENGE 1: REVERSE SPY CODE ===")
# Step 1: Create reversed word list
reversed_words <- c()
for (i in length(story_words):1) {
reversed_words <- c(reversed_words, story_words[i])
}
# Step 2: Print the reversed story
print("๐ ENCODED (Backwards):")
reversed_story <- paste(reversed_words, collapse = " ")
print(...) # TODO: what should we print?
# Step 3: Restore original order
original_words <- c()
for (i in length(reversed_words):1) {
original_words <- c(original_words, reversed_words[...]) # TODO: fill in
}
print("\n๐ DECODED (Original Order):")
original_restored <- paste(original_words, collapse = " ")
print(...) # TODO: what should we print?
# ๐ฏ Challenge 2: Every-Other-Word Spy Code
print("\n๐ === CHALLENGE 2: EVERY-OTHER-WORD SPY CODE ===")
# Step 1: Create empty lists for odd and even positioned words
odd_words <- c()
even_words <- c()
# Step 2: Separate words by position (odd vs even)
for (i in 1:length(story_words)) {
# Note: %% is the remainder operator (great for odd/even)
if (i %% 2 == 1) { # Odd positions (1, 3, 5, ...)
odd_words <- c(odd_words, story_words[...]) # TODO
} else { # Even positions (2, 4, 6, ...)
even_words <- c(even_words, story_words[...]) # TODO
}
}
# Step 3: Create encoded message (odds + separator + evens)
encoded_words <- c(odd_words, "---", even_words)
print("๐ ENCODED (Every-other-word):")
encoded_story <- paste(encoded_words, collapse = " ")
print(encoded_story)
# Step 4: Decode back to original (combine odd and even in correct order)
decoded_words <- c()
for (i in 1:max(length(odd_words), length(even_words))) {
if (i <= length(odd_words)) {
decoded_words <- c(decoded_words, odd_words[...]) # TODO
}
if (i <= length(even_words)) {
decoded_words <- c(decoded_words, even_words[...]) # TODO
}
}
print("๐ DECODED (Original Order):")
decoded_story <- paste(decoded_words, collapse = " ")
print(...) # TODO
# ๐ฎ Bonus: Try Your Own Secret Messages!
print("\n๐ฎ === BONUS: YOUR SECRET MESSAGES ===")
# Try these mini stories or create your own!
mini_secret1 <- "Meet me at the playground after school."
mini_secret2 <- "I found the hidden treasure map."
mini_secret3 <- "The password is rainbow unicorn."
# Your turn: Pick one of the mini secrets and encode it!
my_secret <- "..." # Choose one of the mini_secret messages above
# Split your secret into words
my_words <- unlist(strsplit(my_secret, " "))
# Encode using Method 1 (Reverse) or Method 2 (Every-other-word)
# Write your encoding code here:
๐ก Pro Tips from this spell:
length()tells you how many items are in a list%%finds remainders (great for finding odd/even numbers!)paste(words, collapse = " ")joins words back into sentencesUse
i:1for backwards loops,1:ifor forward loopsc()creates or adds to lists:new_list <- c(old_list, new_item)
3. Magic Libraries: Rโs Treasure Chest of Tools#
Duration: 30 minutes
3.1 What is Open-Source Magic?#
Duration: 5 minutes
๐ Activity: Understanding the Open-source Wizard Community (Programmer Community)#
๐งโโ๏ธ What is Open-Source? Imagine a giant magical library where thousands of friendly wizards from all over the world share their best spells for FREE! Anyone can use them, improve them, and share them back to help other wizards.
๐ช Think of it like this:
๐ Giant Free Library: Thousands of friendly wizard-programmers create useful magical tools and share them for free
๐ค Wizard Community Help: When you have problems, other wizards help you solve them
๐ Always Free: You never have to pay to use these amazing magical tools!
๐ Getting Better Together: When one wizard improves a spell, everyone benefits!
๐ก Examples you know: Google, free games - many of the tools you use every day are built with open-source magic!
3.2 Spell 5: Getting Help with the Magic ? and ??#
Duration: 5 minutes
In R, when you donโt know how something works, just type ? or ?? for help!
๐ Find this spell in Posit Cloud: Look for the file day02_spell05_getting_help.Rmd in your project files!
๐ Activity: The Help Symbol#
๐ Two Types of Magic Help:
The Magic Question Mark ?: When you know the exact function name, use ?
# Want to know how print() works?
?print
# Curious about the mean() function?
?mean
The Super Search ??: When you donโt know exact names but want to explore a topic, use ??
# Find ALL functions related to plotting
??plotting
# Search for anything about statistics
??statistics
๐ก Think of it like this:
?= Ask about one specific spell (like โHow does the fireball spell work?โ)??= Ask to see all spells of a type (like โShow me all fire spells!โ)
3.3 Spell 6: Your First Package - ggplot2#
Duration: 10 minutes
๐ Find this spell in Posit Cloud: Look for the file day02_spell06_first_package.Rmd in your project files!
๐ Activity: Installing Your First Magic Tool#
๐ฆ What is a Package? Think of packages like apps on your parentโs phone - each one adds new powers to R!
๐งโโ๏ธ Remember Open-Source? Packages are the perfect example of what we just learned! Remember how open-source is like a giant magical library where friendly wizards share their best spells? Well, packages ARE those shared spells! Someone created ggplot2 and shared it with the whole world for free, so you can make beautiful charts without having to figure out all the complicated math & code yourself!
๐ญ What is Abstraction? This is a fancy word for โhiding the hard stuff so you can focus on the fun stuff!โ Think of it like this:
When you ride a bike, you donโt need to understand how the gears work inside - you just pedal!
When you use a microwave, you donโt need to know about radio waves - you just press buttons!
When you use ggplot2, you donโt need to know the complicated math & code for drawing - you just tell it what you want!
Thatโs abstraction - the package does all the hard work behind the scenes, so you can focus on creating amazing things! ๐ช
# Step 1: Install the package (like downloading an app)
install.packages("ggplot2")
# Step 2: Load the package (like opening the app)
library(ggplot2)
๐จ Meet ggplot2: This package is like a magical paintbrush that helps us create beautiful pictures with data! And the best part? Someone made this incredible tool and shared it with everyone for FREE!
๐ก Pro Tips
Packages are like apps that add new powers to R
install.packages()downloads them once (like downloading an app)library()opens them each time you want to use them (like opening the app)
3.4 Spell 7: Your First Plot (No Data Yet!)#
Duration: 10 minutes
๐ Find this spell in Posit Cloud: Look for the file day02_spell07_first_plot.Rmd in your project files!
๐ Activity: Drawing Without Data#
๐ญ Letโs start simple: We can make plots even without complicated data! Weโll use simple lists of information.
# Load our magical plotting package
library(ggplot2)
# Simple lists (these are called vectors)
animals <- c("pikachu", "dog", "rabbit", "hamster", "fish")
counts <- c(3, 5, 2, 1, 4)
# Your first ggplot2 magic spell!
ggplot() +
geom_col(aes(x = animals, y = counts))
๐ฎ What does this code do?
c()creates a simple listggplot()starts the magicgeom_col()creates barsaes()tells R what goes where (x and y axes)
โจ Challenge: Try changing the animals or numbers and see what happens!
# Create simple lists
animals <- c("cat", "dog", "rabbit", "hamster", "fish")
counts <- c(3, 5, 2, 1, 4)
print("๐พ Our animal data:")
print(paste("Animals:", paste(animals, collapse = ", ")))
print(paste("Counts:", paste(counts, collapse = ", ")))
# Make your first plot!
plot1 <- ggplot() +
geom_col(aes(x = animals, y = counts))
print(plot1)
# ๐ฏ Challenge 2: Try your own food ratings data
print("\n๐ Creating a plot with your own food ratings data!")
# Create your own lists - change these ... to your favorites!
my_foods <- c(...)
my_ratings <- c(...)
# Make a plot with your data
plot2 <- ggplot() +
geom_col(aes(x = my_foods, y = my_ratings))
print(plot2)
# โจ Challenge: Create your own plot!
# Fill in your own data and create a plot:
# (Run this after replacing the blanks)
my_categories <- c("___", "___", "___") # Fill in 3 things you want to compare
my_values <- c(___, ___, ___) # Fill in numbers for each thing
# Fill in the code below in ... and run them:
my_plot <- ... +
geom_col(aes(x = ..., y = ...))
print(...)
4. Introducing Dataframes: Rโs Magic Tables#
Duration: 20 minutes
4.1 Spell 8: What is a Dataframe?#
Duration: 20 minutes
๐๏ธ What is a Dataframe? Think of it like a super simple spreadsheet - it has rows and columns, just like a table you might make for organizing your Pokemon cards or book collection!
๐ Find this spell in Posit Cloud: Look for the file day02_spell08_dataframes.Rmd in your project files!
๐ Activity: Building Your First Data Table#
# Let's create a simple dataframe about pets
pets <- data.frame(
name = c("Fluffy", "Buddy", "Whiskers"),
type = c("cat", "dog", "cat"),
age = c(3, 5, 2)
)
# Look at our dataframe
print(pets)
๐ฎ What youโll see:
name type age
1 Fluffy cat 3
2 Buddy dog 5
3 Whiskers cat 2
๐ก Understanding the parts:
Columns:
name,type,age(like categories)Rows: Each pet gets one row (like one card in your collection)
data.frame(): The magic function that creates tables
โจ Challenge: Create your own dataframe about your favorite foods, movies, or friends!
# ๐ฏ Challenge 2: Create your own dataframe
print("\n๐ซ Creating a dataframe about your friends!")
# Make a dataframe about your friends (change the data to match your real friends!)
friends <- data.frame(
name = c("Sky", "...", "..."),
favorite_color = c("...", "...", "gre...en"),
age = c(28, ..., ...)
)
print(friends)
# ๐ฏ Challenge 3: Let's explore our dataframes
print("\n๐ Exploring our data:")
# How many rows and columns?
print(paste("Pets dataframe has", nrow(pets), "rows and", ncol(pets), "columns"))
print(paste("Friends dataframe has", nrow(friends), "rows and", ncol(friends), "columns"))
# What are the column names?
print(paste("Pet columns:", paste(names(pets), collapse = ", ")))
print(paste("Friend columns:", paste(names(friends), collapse = ", ")))
# โจ Challenge 4: Create your own dataframe!
# Pick a topic you're interested in and create a dataframe with at least 3 columns and 3 rows
# my_topic <- data.frame(
# column1 = c("___", "___", "___"),
# column2 = c("___", "___", "___"),
# column3 = c(___, ___, ___)
# )
# print(my_topic)
4.2 Spell 9: Visualizing Your Data Magic#
Duration: 20 minutes
๐ Find this spell in Posit Cloud: Look for the file day02_spell09_visualizing_dataframes.Rmd in your project files!
๐จ Now that youโve created your own dataframe in Spell 8, letโs turn it into beautiful pictures! Just like how artists use different brushes and colors, we can use ggplot2 to make our data look amazing in many different ways!
๐ Activity: From Data to Art#
๐ฏ Your Mission: Take the dataframe you created in Spell 8 and transform it into stunning visual art! Weโll explore different chart styles, colors, and themes - itโs like having a magical art studio for your data!
library(ggplot2)
# ๐ฏ Challenge 1: Visualize your dataframe from Spell 8
# Use the dataframe you created in Spell 8 here (example shown):
my_data <- data.frame(
name = c("Pizza", "Ice Cream", "Tacos", "Cookies"),
rating = c(10, 9, 8, 10),
category = c("dinner", "dessert", "dinner", "dessert")
)
ggplot(my_data, aes(x = name, y = rating)) +
geom_col()
# ๐ฏ Challenge 2: Add some color magic!
ggplot(my_data, aes(x = name, y = rating)) +
geom_col(fill = "orange") # Try different colors: "red", "green", "purple", "orange"
# Try this too - different color for each bar!
ggplot(my_data, aes(x = name, y = rating, fill = name)) +
geom_col() +
theme(text = element_text(size = 16), # Set text size for all elements
plot.title = element_text(size = 20), # Set title size
axis.title = element_text(size = 18), # Set axis title size
axis.text = element_text(size = 19)) # Set axis text size
# ๐ฏ Challenge 3: Make it professional with themes!
ggplot(my_data, aes(x = name, y = rating)) +
geom_col(fill = "pink") +
theme_minimal() + # Makes it look clean and modern!
theme(text = element_text(size = 16), # Set text size for all elements
plot.title = element_text(size = 20), # Set title size
axis.title = element_text(size = 18), # Set axis title size
axis.text = element_text(size = 19)) # Set axis text size
# Try other themes: theme_classic(), theme_dark(), theme_void()
# ๐ฏ Challenge 4: Add titles and labels
ggplot(my_data, aes(x = name, y = rating)) +
geom_col(fill = "purple") +
theme_minimal() +
labs(
title = "My Favorite Foods Rating", # Main title
x = "Food Items", # X-axis label
y = "How Much I Like It (1-10)" # Y-axis label
) +
theme(text = element_text(size = 16), # Set text size for all elements
plot.title = element_text(size = 20), # Set title size
axis.title = element_text(size = 18), # Set axis title size
axis.text = element_text(size = 19)) # Set axis text size
# ๐ฏ Challenge 5: Color by category (if your data has categories)
ggplot(my_data, aes(x = name, y = rating, fill = category)) +
geom_col() +
theme_minimal() +
labs(title = "My Food Ratings by Category") +
theme(text = element_text(size = 16), # Set text size for all elements
plot.title = element_text(size = 20), # Set title size
axis.title = element_text(size = 18), # Set axis title size
axis.text = element_text(size = 19)) # Set axis text size
๐ก Pro Tips for this spell:
aes()tells ggplot what data to use for x, y, and colorsfill = "color"makes all bars the same colorfill = column_namemakes each category a different colorDifferent themes:
theme_minimal()makes charts look clean and moderntheme_classic()gives charts a traditional newspaper looktheme_dark()creates charts with dark backgroundstheme_void()removes all grid lines for a minimal style
labs()adds titles and labels to make charts easier to understandYou can save your plot:
ggsave("my_chart.png")
5. ๐ Pro Tips Cheatsheet#
R Markdown Files (.Rmd)#
.Rmdis like a magic notebook: where you mix hand-written notes with codeCode chunks: Put R code inside special fences:
{r}` andText/paragraphs: Just type normally, use
#for titles,**bold**for emphasisTwo viewing modes:
Source(raw code/text) vsVisual(formatted nicely)Knitbutton: Turns your .Rmd into beautiful HTML webpage or PDFRun chunks individually: Click โถ๏ธ green arrow to run one piece at a time
For Loops#
Use
for (i in 1:10)to repeat actions 10 timesAlways use curly braces
{}for multiple commandsprint()shows results inside loopsThink of
ias a magical counter that changes each time
Packages & Getting Help#
install.packages("package_name")downloads new tools (like downloading an app)library(package_name)loads tools for use (like opening the app)Type
?function_nameto get help on any specific functionType
??topicto search for ALL functions related to a topicRemember:
?= specific help,??= topic searchOpen-source connection: Packages ARE open-source! Like a giant library where friendly wizards share their best spells for free
Abstraction: Packages hide the hard math & code so you can focus on creating cool things
Think of packages like bike gears - you donโt need to understand how they work, just use them!
Simple Plotting with ggplot2#
ggplot()starts every plotgeom_col()creates bar chartsaes(x = , y = )tells R what goes on each axisc()creates simple lists of data
Dataframes#
data.frame()creates tables with rows and columnsThink of dataframes like spreadsheets or card collections
Each column is a category (like name, age, type)
Each row is one item (like one person or one pet)
Data Visualization Magic#
aes()tells ggplot what data to use for x, y, and colorsfill = "color"makes all bars the same colorfill = column_namemakes each category a different colorDifferent themes:
theme_minimal()makes charts look clean and moderntheme_classic()gives charts a traditional newspaper looktheme_dark()creates charts with dark backgroundstheme_void()removes all grid lines for a minimal style
labs()adds titles and labels to make charts easier to understandYou can save your plot:
ggsave("my_chart.png")
6. ๐ Troubleshooting Cheatsheet#
Common Loop Problems#
๐ Error: โobject not foundโ
What it means: R canโt find a variable
Why it happens: Variable not created or typo in name
The Fix: Check spelling and make sure variable exists
๐ Error: โmissing closing braceโ
What it means: Forgot to close
{}Why it happens: Every
{needs a matching}The Fix: Count your braces and add the missing one
Package Problems#
๐ Error: โcould not find functionโ
What it means: Package not loaded
Why it happens: Forgot to run
library()The Fix: Load the package first:
library(ggplot2)
๐ Error: โthere is no package calledโฆโ
What it means: Package not installed
Why it happens: Need to download the package first
The Fix: Run
install.packages("package_name")first
Simple Plotting Problems#
๐ Plot doesnโt show
What it means: Code ran but no plot appeared
Why it happens: Missing parts of the ggplot command
The Fix: Make sure you have
ggplot() + geom_something()