--- title: "Week 3: Simulation, Loops, and if/else Statements" date: "January 25, 2018" output: html_document --- ```{r setup, include=FALSE} knitr::opts_chunk\$set(echo = TRUE) knitr::opts_chunk\$set(cache=TRUE) library(knitr) knitr::knit_hooks\$set(mysize = function(before, options, envir) { if (before) return(options\$size) }) ``` ## Roulette Simulation in R ```{r roulette, mysize=TRUE, size = '\\scriptsize'} RouletteSpin <- function(num.spins){ # function to simulate roulette spins # ARGS: number of spins # RETURNS: result of each spin outcomes <- data.frame(number = c('00','0', as.character(1:36)), color=c('green','green','red','black','red','black', 'red','black','red','black','red','black', 'black','red','black','red','black', 'red','black','red','red','black', 'red','black','red','black','red', 'black','red','black','black','red', 'black','red','black','red','black','red')) return(outcomes[sample(38,num.spins,replace=T),]) } kable(RouletteSpin(2), row.names=F) ``` ## Exercise: Probability of Red, Green, and Black 1. Calculate/Derive the probability of landing on green, red, and black. 2. How can the `RouletteSpin()` function be used to compute or approximate these probabilities? ## Exercise: Simulation Questions - Part 2 Now what happens if we: 1. run the simulation again with the same number of trials? 2. run the simulation with more trials, say 1 million? ## Exercise: Conditions in R We have touched on many of these before, but here are some examples of expressions (conditions) in R. ```{r, eval=FALSE} pi > 3 & pi < 3.5 c(1,3,5,7) %in% 1:3 1:3 %in% c(1,3,5,7) rand.uniform <- runif(n = 1, min = 0, max = 1) rand.uniform < .5 ``` ## Exercise: Conditional Expression Write a conditional statement that takes a playing card with two arguments: - (`card.number <- '4'` and `card.suit <- 'C'` = 4 of clubs or `card.number <-'K'` and `card.suit <- 'H'` = King of hearts) and - Print `Yes` if the card is a red face card and `No` otherwise. Verify this works using the following inputs: - `card.number <- 'J'` and `card.suit <- 'D'` - `card.number <- 'Q'` and `card.suit <- 'S'` ## Exercise: Loops Assume you plan to wager \$1 on red for ten roulette spins. If the outcome is red you win a dollar and otherwise you lose a dollar. Write a loop that simulates ten rolls and determines your net profit or loss. ```{r} #hint: to get color from a single spin use RouletteSpin(1)[2] ```