# This line is a comment. It is ignored by R. ### INFRASTRUCTURE ### # This first chunk of code defines a function for out later use. In RStudio, # click on the word 'flipCoins' below and then click the Run button. flipCoins <- function(n=1) { sample(0:1, n, replace=TRUE) } # Similarly, execute the following function definition by clicking on the first # line and clicking the Run button. rollDice <- function(n=1) { sample(1:6, n, replace=TRUE) } # Execute this next function definition too. drawCards <- function(n=1) { sample(1:52, n, replace=TRUE) } cardRank <- function(card) { card %% 13 + 1 } cardSuit <- function(card) { card %/% 13 + 1 } ### BASIC EXAMPLES ### # Here are some examples with coins. 0 means tails and 1 means heads, if you # prefer that terminology. flipCoins() flipCoins(10) flipCoins(100) # Here is an easy way to flip many coins and count the number of heads. sum(flipCoins(100)) # Here's a histogram visualization of the results. hist(flipCoins(100)) # Here are some examples with dice. rollDice() rollDice(10) rollDice(100) hist(rollDice(100)) # Here is the average of 1,000 rolls of dice. Does the answer make sense? sum(rollDice(100)) / 100 # Here are some examples with cards. drawCards() drawCards(10) drawCards(100) hist(drawCards(100)) # Our card functions identify a card as a number between 1 and 52. If you want # to decode that number into a rank between 1 and 13 and a suit between 1 and # 4, here's how. card <- drawCards() card cardRank(card) cardSuit(card) # Here are 1,000 cards, with histograms of their ranks and suits. cards <- drawCards(1000) hist(sapply(cards, cardRank)) hist(sapply(cards, cardSuit)) ### SUMS OF DICE PAIRS ### # These lines define a function that rolls two dice and sums them. sumTwoDice <- function(n=1) { replicate(n, sum(rollDice(2))) } # Here are is a histogram of 1,000 results. Can you explain the shape? hist(sumTwoDice(1000)) # As we will learn later, the 'correct, exact' answer is as shown in the # following graph. Our 1,000-trial experiment above yields an approximation to # this exact answer. plot(x=(2:12), y=c(1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1) / 36)