R
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Data Structures
-
Section 4: Data Manipulation
-
Section 5: Visualization and Statistics
-
Section 6: Advanced R
-
Section 7: Practical Projects
-
Section 8: Interview Practice
-
Section 9: More Practice Exercises
-
Section 10: Shiny Apps in Depth
-
Section 11: More Data Wrangling
-
Section 12: Tidyverse Deep Dive
-
Section 13: Statistical Modeling Deep Dive
-
Section 14: Machine Learning in R
-
Section 15: R Visualization Deep Dive
-
Section 16: R Package Development Deep Dive
-
Section 17: R for Reproducible Research
-
Section 18: R and Databases
-
Section 19: R Performance Optimization
-
Section 20: Bioinformatics and Specialized R
-
Section 21: More Shiny Practice
-
Section 22: More Practice Exercises
-
Section 23: R Data Structures Deep Dive
-
Section 24: More Interview and Review
-
Section 25: R for Business Analytics
-
Section 26: R Text Mining and NLP
-
Section 27: R Spatial Data Analysis
-
Section 28: R Deep Learning
-
Section 29: Advanced Statistical Techniques
-
Section 30: R Object Systems Deep Dive
-
Section 31: R Environments and Metaprogramming
-
Section 32: R for Finance
-
Section 33: R for Clinical and Health Data
-
Section 34: More Shiny Advanced Practice
-
Section 35: R Data Cleaning Deep Dive
-
Section 36: R Reporting Automation
-
Section 37: More Practical Projects Round 2
-
Section 38: R Ecosystem and Career
-
Section 39: More Visualization Practice
-
Section 40: R for Experimentation
-
Section 41: R for Genomics and Bioinformatics Deep Dive
-
Section 42: R for Marketing Analytics
-
Section 43: R Data Import/Export Deep Dive
-
Section 44: R String Processing Deep Dive
-
Section 45: R for Actuarial and Insurance Analytics
-
Section 46: R Testing and Quality Assurance Deep Dive
-
Section 47: R Version Control and Collaboration
-
Section 48: R Advanced Functional Programming
-
Section 49: R for Supply Chain and Operations
-
Section 50: More Practice Exercises Round 3
-
Section 51: R Dashboards and BI Integration
-
Section 52: R Data Governance and Ethics
-
Section 53: More Modeling Practice
-
Section 54: R Final Capstone Projects
-
Section 55: R for Sports Analytics
-
Section 56: More Interview Practice Round 2
-
Section 57: R Networking and APIs
-
Section 58: R for Environmental Science
-
Section 59: R Notebook and Documentation Practices
-
Section 60: More Data Wrangling Mastery
-
Section 61: R for A/B Testing at Scale
-
Section 62: R Package Ecosystem Deep Dive
159: Multi-Armed Bandit Simulations in R
Imagine you've just walked into a casino and you're staring at a row of five different slot machines. You know that each machine has a different probability of paying out, but the casino isn't telling you which is which. You have 100 tokens. Now you're faced with a classic dilemma: do you spend your tokens testing every single machine to find the one with the highest payout (exploration), or do you find one that pays out once and just keep pulling that lever for the rest of the night (exploitation)?
In software engineering and data science, we call this the Multi-Armed Bandit problem. It's the core logic behind everything from A/B testing website headers to how Netflix decides which movie thumbnails to show you. If you exploit too early, you might miss the "jackpot" machine. If you explore too long, you waste tokens on losers.
Defining the 'Arms' of our Bandit
To simulate this in R, we first need to define our environment. In our case, the "arms" are just a vector of probabilities. I like to think of this as the "ground truth" that our simulation is trying to discover.
# The ground truth: 5 machines with different win probabilities
true_probs <- c(0.05, 0.12, 0.45, 0.20, 0.08)
n_arms <- length(true_probs)
n_trials <- 1000
epsilon <- 0.1 # 10% of the time we explore
Here, the third machine is the clear winner at 45%. Our code doesn't know that, though; it only knows what happens after it "pulls the lever."
The Tug-of-War: Exploration vs. Exploitation
The most straightforward way to handle this is the $\epsilon$-greedy (epsilon-greedy) algorithm. The logic is simple: most of the time, we pick the best machine we've found so far. But occasionally—controlled by $\epsilon$—we intentionally pick a random machine just to see if we were wrong about our current favorite.
Let's build the simulation loop. I'll use a vector to track our estimated means for each arm and another to track how many times we've pulled each lever.
# Initialize our knowledge
est_means <- rep(0, n_arms)
counts <- rep(0, n_arms)
total_reward <- 0
for (i in 1:n_trials) {
# Decide: Explore or Exploit?
if (runif(1) < epsilon) {
# Exploration: Pick a random arm
chosen_arm <- sample(1:n_arms, 1)
} else {
# Exploitation: Pick the arm with the current best estimate
chosen_arm <- which.max(est_means)
}
# Simulate the payout (1 for win, 0 for loss)
reward <- rbinom(1, 1, true_probs[chosen_arm])
# Update our knowledge using the incremental average formula
counts[chosen_arm] <- counts[chosen_arm] + 1
est_means[chosen_arm] <- est_means[chosen_arm] + (reward - est_means[chosen_arm]) / counts[chosen_arm]
total_reward <- total_reward + reward
}
print(paste("Total Reward:", total_reward))
print("Estimated Probabilities:")
print(est_means)
Why the Incremental Average Matters
You'll notice I didn't just sum the rewards and divide by the count inside the loop. I used est_means[chosen_arm] + (reward - est_means[chosen_arm]) / counts[chosen_arm]. This is a little trick to avoid storing a massive list of every single result. It updates the average on the fly, which is much more memory-efficient when you're running millions of trials—something you'll frequently do in production simulations.
If you run this code, you'll see that est_means usually gets very close to true_probs. But more importantly, if you look at the counts vector, you'll see the simulation spent the vast majority of its time pulling the arm with the 0.45 probability. That's the $\epsilon$-greedy strategy working: it explored enough to find the winner, then exploited that winner to maximize the total reward.
📋 Practical Task
Simulating Ad Campaign Optimization
You are managing an online ad campaign with three different banner designs (Arms A, B, and C). Your goal is to maximize the number of clicks. The actual click-through rates (CTR) are: Arm A = 2%, Arm B = 8%, and Arm C = 5%.
Write an R script to simulate 2,000 impressions using an $\epsilon$-greedy strategy. However, I want you to test the impact of the exploration rate. Run the simulation twice: once with epsilon = 0.01 (1% exploration) and once with epsilon = 0.2 (20% exploration).
Your code should output the total rewards (clicks) and the final estimated probabilities for both scenarios. In your results, observe which epsilon value led to a higher total reward and why the "over-exploring" agent might have a more accurate estimate of the losing arms but a lower total payout.
There are no comments for now.