# Exercise 16: confidence interval and tests for two proportions
# In this exercise we will use the results from the opinion polls from Norstat from April and March 2013 to investigate the change in the support for some political parties.
# In March 2013 Norstat asked n1=969 individuals which party they would support if there had been election to the parliament tomorrow. Of these y1=310 would have voted H?yre.
# One month later, in April, n2=968 persons were interviewed and y2=303 of these would have voted H?yre.
# Question a)
# We start out by estimating the change in the support for H?yre with a 95 % confidence interval (cf. slide 6)
n1=969
y1=310
p1=y1/n1
se1=sqrt(p1*(1-p1)/n1)
n2=968
y2=303
p2=y2/n2
se2=sqrt(p2*(1-p2)/n2)
se=sqrt(se1^2+se2^2)
change=p1-p2
margin=1.96*se
lower=change-margin
upper=change+margin
cbind(change,margin,lower,upper)
# Perform these commands and comment on the results. Make sure that you understand the commands!
# Question b)
# We then test the null hypothesis that the support for H?yre has not changed from March to April (cf. slide 8)
p=(y1+y2)/(n1+n2)
se0=sqrt(p*(1-p)/n1+p*(1-p)/n2)
z=(p1-p2)/se0
pval=2*(1-pnorm(abs(z)))
cbind(z,pval)
# Perform these commands and comment on the results.
# Is the null hypothesis rejected or not? How does this relate to the confidence interval computed earlier?
# Question c)
# R has a command for comparing two proportions
hoyre=matrix(c(y1,y2,n1-y1,n2-y2),nrow=2) # give the data for H?yre in a 2x2 table (cf. slide 10)
prop.test(hoyre,correct=F)
# Perform these commands and check that the results agree with those obtained earlier.
# The prop.test-command give a chi squared statistic, not a z-value as we computed earlier. What is the relation between the two?
# Question d)
# We will then take a look at the results for Arbeiderpartiet (Ap). In March 263 of the 969 persons who were interviewed would have voted Arbeiderpartiet; while in April 238 of the 968 interviewed would have voted Arbeiderpartiet.
# Estimating the change in the support for Arbeiderpartiet with a 95 % confidence interval.
# Also test the null hypothesis the support for Arbeiderpartiet has not changed from March to April.
# What are your conclusions?