############################################### ## Author: Joshua M. Tebbs ## Date: 30 June 2018 ## Update: 10 November 2018 ## STAT 511 course notes: R Code ## Chapter 2 ############################################### # Figure 2.1 # Page 2 n = 10000 # number of simulations flip = rbinom(n,1,0.5) # Create plot of the relative frequencies # Initialise rel.freq = flip*0 for (i in 1:n){ rel.freq[i] = sum(flip[1:i])/i } plot(rel.freq,ylab="Relative frequency",xlab="Number of flips",type="o",pch=20,cex.lab=1.25) abline(h=0.5,lty=2) sum(flip) # Figure 2.2 # Page 4 n = 10000 # number of simulations M = 10 # number of men event = seq(1,n,1)*0 hats = matrix(0,n,M) for (i in 1:n){ hats[i,]<-sample(seq(1,M,1),replace=FALSE) match = hats[,1]*0 for (j in 1:M){ if (hats[i,j]==j) match[j]<-1 else match[j]<-0 } if (sum(match)>0) event[i]<-1 else event[i]<-0 } sum(event) # Create plot of the relative frequencies # Initialise rel.freq = event*0 for (i in 1:n){ rel.freq[i] = sum(event[1:i])/i } plot(rel.freq,ylab="Relative frequency",xlab="Number of trials",type="o",pch=20,cex.lab=1.25) # Figure 2.3 # Page 5 n = 10000 # number of simulations M = 50 # number of students event = seq(1,n,1)*0 birthday = matrix(0,n,M) for (i in 1:n){ birthday[i,]<-sample(seq(1,365,1),size=M,replace=TRUE) if (length(unique(birthday[i,]))