-
Notifications
You must be signed in to change notification settings - Fork 0
/
consistency.R
40 lines (31 loc) · 1.08 KB
/
consistency.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
## Coin flip simulation to demonstrate consistency
# Set total number of samples:
n <- 1000
# Set population proportion (of heads):
p <- 0.5
# Flip coin n times
coinflips <- rbinom(n, 1, p)
# This function calculates the proportion (of heads) in a sample
prop <- function(i, flips){
sum(flips[1:i])/i
}
# Calculate the proportion after each flip
p.hat <- sapply(1:n, prop, flips=coinflips)
# Plot the sample proportion at each trial
# The red line indicates the true sample propotion
plot(p.hat, type='l', ylim=c(0,1),
xlab="Trial", ylab="Sample Proportion"); abline(h=p, col='red')
# Do the whole thing a bunch of times and add to plot:
for(i in 1:25){
# Flip coin n times
coinflips <- rbinom(n, 1, p)
# This function calculates the proportion (of heads) in a sample
prop <- function(i, flips){
sum(flips[1:i])/i
}
# Calculate the proportion after each flip
p.hat <- sapply(1:n, prop, flips=coinflips)
# Plot the sample proportion at each trial
# The red line indicates the true sample propotion
points(p.hat, type='l')
}