Friday, 28 February 2014

Doing loops and testing them


To simulate rolling a dice

outcome6<-c(1,2,3,4,5,6)   #this is because there are 6 sides to the dice

sim1000<-sample(outcome6,size=1000, replace=TRUE)


Relative histograms

This website looks useful
http://www.statmethods.net/graphs/bar.html

Here is a similar example of what we were trying to do

Simple Bar Plot

# Simple Bar Plot
counts <- table(mtcars$gear)
barplot(counts, main="Car Distribution",
   xlab="Number of Gears")

simple barplot

The following will work for your simulated data

# Relative histogram of 100 rolls
count<-table(sim100)

 barplot(count/100,main="simulated rolling of a dice - 100 times",
    xlab="Number on dice", ylab = "Proportion of rolls")



Sequences

Rle – counts sequences of the same number, gives the count of each sequence, with the number in the sequence

streak[[2]] - this count of the sequence corresponding to the 2nd item (in this case a "T")

max(streak) - the highest sequence regardless of "h" or "T"


Loops

(Write a for loop that stores in an object the longest run of consecutive heads in 1000 sets of 200 coin tosses
coinmax<-rep(0,1000)
for (i in 1:1000) {
  coin200 <- sample(outcomes, size = 200, replace = TRUE) 
  streak <- tapply(rle(coin200)$lengths, rle(coin200)$values, max)

coinmax[i]<-streak[[1]]

 }

max(coinmax) - This will print out the highest number of sequences out of the 1000 samples