Excercise 2
Help: you can write a series of R commands into a file, and then execute them all in a row by doing
□
source(
filename
)
1a. By simulating 10000 times flipping a coin 10 times, make a table of the probability to have heads
show up 0 times, 1 time, twice, and so on.
□
flip=matrix(sample(0:1,10000*10,rep=T),10000,10)
□
count=apply(flip,1,sum)
□
table(count)/length(count)
count
0
1
2
3
4
5
6
7
8
9
10
0.0007 0.0114 0.0436 0.1171 0.2102 0.2377 0.2089 0.1188 0.0424 0.0080 0.0012
□
hist(count,breaks=-0.5:10.5,prob=T);v()
Histogram of count
count
Density
0
2
4
6
8
10
0.000.050.100.150.20
□
1b. If someone flipped a coin, and got 1 head, and 9 tails, we would like to test the hypothesis that the
coin is unbiased. We will do this by calculating the probability that an unbiased coin flipped 10 times
gives 0 or 1 heads, or 0 or 1 tails. Calculate this probability.
□
Tab=table(count)/length(count)
1
□
Tab
count
0
1
2
3
4
5
6
7
8
9
10
0.0007 0.0114 0.0436 0.1171 0.2102 0.2377 0.2089 0.1188 0.0424 0.0080 0.0012
□
sum(count
□ = 1
count
□
= 10-1)/length(count)
[1] 0.0213
□
Notice that the ’
’ symbol means ’or’ and the ’&’ symbol means ’and’.
1c. How many heads/tails out of 10 would cause one to reject the hypothesis that the coin is unbiased at
the 5% level? That means, how many heads/tails give a probability that is lower than 5% as calculated
above.
□
sapply(0:5,function(i) sum(count
□ = i
count
□
= 10-i)/length(count))
[1] 0.0019 0.0213 0.1073 0.3432 0.7623 1.0000
□
At a 5% level, we would reject 1:9 but not 2:8.
1d. With the command sample(0:1, 10, prob=c(0.3,0.7)) you can simulate a coin flip of a biased
coin. Out of 1000 coin flips of length 10 that are biased as above, how many come up significant at the
5% level? I.e. how often do you get as low a number as you calculated in 1c or worse? How many come
up significant for an unbiased coin? How about c(0.1,0.9) ?
□
bflip=matrix( sample(0:1, 10*1000, rep=T, prob=c(0.3,0.7) ), 1000, 10)
□
bcount=apply(bflip,1,sum)
Since we reject at the 5% level 0:10, 1:9,