๐Ÿช„ Day 2: Loops and Magic Libraries

Contents

๐Ÿช„ Day 2: Loops and Magic Libraries#

Oda the Data Otter learns to repeat magic spells and discovers Rโ€™s treasure box of helpful tools!

loop

๐ŸŽฏ 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

hello_penguine

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:

  1. 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โ€

  2. 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?

  3. 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
}
  1. Reflect (1 min):

    • Does everyone get their own category?

    • What surprised you about your groupโ€™s similarities and differences?

hello2

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 }

  • number is like a counter that changes each time (number = 1, then 2, then 3โ€ฆ)

  • 1:10 means โ€œ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!
}
ginger

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 .R files - just plain code

  • Day 2+: We use .Rmd files - code + beautiful formatting + notes all in one!

rmd file

๐ŸŽฏ Key Parts of .Rmd Files:#

1. Text/Paragraphs ๐Ÿ“

  • Click insert โ€“> paragraph to add a new paragraph block

  • Just type normally like this sentence

  • Use # for big titles, ## for smaller titles

  • Use **bold** or *italic* for emphasis

2. Code Chunks ๐Ÿ’ป

  • Click insert โ€“> Executable Cell โ€“> R to add a new paragraph block

  • Code 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:

  • ๐Ÿ“ Source Mode: See the raw code and text (like peeking behind the magic curtain)

  • ๐Ÿ‘๏ธ Visual Mode: 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.

repeat

๐ŸŽˆ 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 i as 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 names

  • paste() 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!

sing

๐ŸŽˆ 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

performance

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.โ€

forest

๐ŸŽˆ 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 sentences

  • Use i:1 for backwards loops, 1:i for forward loops

  • c() 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!

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)

woo

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))
dance

๐Ÿ”ฎ What does this code do?

  • c() creates a simple list

  • ggplot() starts the magic

  • geom_col() creates bars

  • aes() 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!

friend
# ๐ŸŽฏ 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 colors

  • fill = "color" makes all bars the same color

  • fill = column_name makes each category a different color

  • Different themes:

    • theme_minimal() makes charts look clean and modern

    • theme_classic() gives charts a traditional newspaper look

    • theme_dark() creates charts with dark backgrounds

    • theme_void() removes all grid lines for a minimal style

  • labs() adds titles and labels to make charts easier to understand

  • You can save your plot: ggsave("my_chart.png")

visualization

5. ๐Ÿ“‹ Pro Tips Cheatsheet#

R Markdown Files (.Rmd)#

  • .Rmd is like a magic notebook: where you mix hand-written notes with code

  • Code chunks: Put R code inside special fences: {r}` and

  • Text/paragraphs: Just type normally, use # for titles, **bold** for emphasis

  • Two viewing modes: Source (raw code/text) vs Visual (formatted nicely)

  • Knit button: Turns your .Rmd into beautiful HTML webpage or PDF

  • Run chunks individually: Click โ–ถ๏ธ green arrow to run one piece at a time

For Loops#

  • Use for (i in 1:10) to repeat actions 10 times

  • Always use curly braces {} for multiple commands

  • print() shows results inside loops

  • Think of i as 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_name to get help on any specific function

  • Type ??topic to search for ALL functions related to a topic

  • Remember: ? = specific help, ?? = topic search

  • Open-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 plot

  • geom_col() creates bar charts

  • aes(x = , y = ) tells R what goes on each axis

  • c() creates simple lists of data

Dataframes#

  • data.frame() creates tables with rows and columns

  • Think 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 colors

  • fill = "color" makes all bars the same color

  • fill = column_name makes each category a different color

  • Different themes:

    • theme_minimal() makes charts look clean and modern

    • theme_classic() gives charts a traditional newspaper look

    • theme_dark() creates charts with dark backgrounds

    • theme_void() removes all grid lines for a minimal style

  • labs() adds titles and labels to make charts easier to understand

  • You 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()