R code for the “trust in clergy” problem we discussed in class

#Trust levels in 2010 and 2015

p2010 <- .6

p2015 <- .56

#Sample size for the poll

n <- 1000

#standard erros for the poll in 2010 and 2015

SE2010 <- sqrt((p2010*(1-p2010))/n)

SE2015 <- sqrt((p2015*(1-p2015))/n)

#SE of the difference between polls

SEdiff <- sqrt(SE2010^2 + SE2015^2)

#Z-test

z_test <- (p2015 – p2010) / SEdiff

#P-value

pnorm(z_test)

#Box Model

pop <- 1000000 #number of tickets in the box

#writing 1’s and 0’s on the tickets

box <- c(rep(1, pop*p2010), rep(0, pop*(1-p2010)))

#running the model

diffs <- NA

for (i in 1:10000){

samp1 <- sample(x = box, size = n)

samp2 <- sample(x = box, size = n)

diffs[i] <- mean(samp1) – mean(samp2)

}

#Distribution of the differences

hist(diffs)

abline(v=-0.06, col = “red”)

length(diffs) #total number of differences we calculated

#number of times diff was more than what we observed

length(diffs[diffs >= (p2010 – p2015)])

#p-value value via box model

length(diffs[diffs >= (p2010 – p2015)]) / length(diffs)