-
Notifications
You must be signed in to change notification settings - Fork 0
/
inf_for_categorical_data_Coursera.Rmd
356 lines (271 loc) · 15.4 KB
/
inf_for_categorical_data_Coursera.Rmd
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
---
title: "Inference for categorical data"
output: statsr:::statswithr_lab
---
<div id="instructions">
Complete all **Exercises**, and submit answers to **Questions** on the Coursera
platform.
</div>
In August of 2012, news outlets ranging from the [Washington Post](http://www.washingtonpost.com/national/on-faith/poll-shows-atheism-on-the-rise-in-the-us/2012/08/13/90020fd6-e57d-11e1-9739-eef99c5fb285_story.html) to the [Huffington Post](http://www.huffingtonpost.com/2012/08/14/atheism-rise-religiosity-decline-in-america_n_1777031.html) ran a story about the rise of atheism in America. The source for the story was a poll that asked people, "Irrespective of whether you attend a place of worship or not, would you say you are a religious person, not a religious person or a convinced atheist?" This type of question, which asks people to classify themselves in one way or another, is common in polling and generates categorical data. In this lab we take a look at the atheism survey and explore what's at play when making inference about population proportions using categorical data.
## Getting Started
### Load packages
In this lab we will explore the data using the `dplyr` package and visualize it
using the `ggplot2` package for data visualization. The data can be found in the
companion package for this course, `statsr`.
Let's load the packages.
```{r load-packages, message=FALSE}
library(statsr)
library(dplyr)
library(ggplot2)
```
### The survey
The press release for the poll, conducted by WIN-Gallup International, can be accessed [here](http://www.wingia.com/web/files/richeditor/filemanager/Global_INDEX_of_Religiosity_and_Atheism_PR__6.pdf).
Take a moment to review the report then address the following questions.
1. How many people were interviewed for this survey?
<ol>
<li> A poll conducted by WIN-Gallup International surveyed 51,000 people from 57 countries. </li>
<li> A poll conducted by WIN-Gallup International surveyed 52,000 people from 57 countries. </li>
<li> A poll conducted by WIN-Gallup International surveyed 51,917 people from 57 countries. </li>
<li> A poll conducted by WIN-Gallup International surveyed 51,927 people from 57 countries. </li>
</ol>
Answer 4
2. Which of the following methods were used to gather information?
<ol>
<li> Face to face </li>
<li> Telephone </li>
<li> Internet </li>
<li> All of the above </li>
</ol>
Answer 4
3. True / False: In the first paragraph, several key findings are reported. These percentages appear to be **sample statistics**.
<ol>
<li> True </li>
<li> False </li>
</ol>
TRUE
4. True / False:The title of the report is "Global Index of Religiosity and Atheism". To generalize the report's findings to the global human population, We must assume that the sample was a random sample from the entire population in order to be able to generalize the results to the global human population. This seems to be a reasonable assumption.
<ol>
<li> True </li>
<li> False </li>
</ol>
TRUE
### The data
Turn your attention to Table 6 (pages 15 and 16), which reports the sample size and response percentages for all 57 countries. While this is a useful format to summarize the data, we will base our analysis on the original data set of individual responses to the survey. Load this data set into R with the following command.
```{r load-data}
data(atheism)
```
5. What does each row of Table 6 correspond to?
<ol>
<li> Countries </li>
<li> Individual Persons </li>
<li> Religions </li>
</ol>
ANSWER 1
6. What does each row of `atheism` correspond to?
<ol>
<li> Countries </li>
<li> Individual Persons </li>
<li> Religions </li>
</ol>
ANSWER 2
To investigate the link between these two ways of organizing this data, take a look at the estimated proportion of atheists in the United States. Towards the bottom of Table 6, we see that this is 5%. We should be able to come to the same number using the `atheism` data.
Create a new dataframe called `us12` that contains only the rows in `atheism` associated with respondents to the 2012 survey from the United States:
```{r us-atheism}
us12 <- atheism %>%
filter(nationality == "United States" , atheism$year == "2012")
```
7. Next, calculate the proportion of atheist responses in the United States in 2012, i.e. in `us12`. True / False: This percentage agrees with the percentage in Table~6.
<ol>
<li> True </li>
<li> False </li>
</ol>
TRUE
```{r perc-atheist-us12}
# type your code for Question 7 here, and Knit
total_us <- us12 %>% summarise(n())
total_us
atheist_us <- us12 %>% filter(response == "atheist") %>% summarise(n())
atheist_us
atheist_us_por <- atheist_us / total_us
atheist_us_por
```
## Inference on proportions
As was hinted earlier, Table 6 provides **sample statistics**, that is, calculations made from the sample of 51,927 people. What we'd like, though, is insight into the population **population parameters**. You answer the question, "What proportion of people in your sample reported being atheists?" with a statistic; while the question "What proportion of people on earth would report being atheists" is answered with an estimate of the parameter.
The inferential tools for estimating population proportion are analogous to those used for means in the last lab: the confidence interval and the hypothesis test.
<div id="exercise">
**Exercise**: Write out the conditions for inference to construct a 95% confidence interval for the proportion of atheists in the United States in 2012. Are you confident all conditions are met?
</div>
If the conditions for inference are reasonable, we can either calculate the standard error and construct the interval by hand, or allow the `inference` function to do it for us.
```{r us-atheism-ci}
SE <- sqrt(atheist_us_por * (1 - atheist_us_por) / total_us)
qnorm(0.975)
c(atheist_us_por - qnorm(0.975) * SE , atheist_us_por + qnorm(0.975) * SE )
# which is equivalent to:
inference(y = response, data = us12, statistic = "proportion", type = "ci", method = "theoretical", success = "atheist")
```
Note that since the goal is to construct an interval estimate for a proportion, it's necessary to specify what constitutes a ``success'', which here is a response of `atheist`.
Although formal confidence intervals and hypothesis tests don't show up in the report, suggestions of inference appear at the bottom of page 7: "In general, the error margin for surveys of this kind is $\pm$ 3-5% at 95% confidence."
<div id="exercise">
**Exercise**: Imagine that, after reading a front page story about the latest public opinion poll, a family member asks you, "What is a margin of error?" In one sentence, and ignoring the mechanics behind the calculation, how would you respond in a way that conveys the general concept?
</div>
8. Based on the R output, what is the margin of error for the estimate of the proportion of the proportion of atheists in US in 2012?
<ol>
<li> The margin of error for the estimate of the proportion of atheists in the US in 2012 is 0.05. </li>
<li> The margin of error for the estimate of the proportion of atheists in the US in 2012 is 0.025. </li>
<li> The margin of error for the estimate of the proportion of atheists in the US in 2012 is 0.0135. </li>
</ol>
ANSWER 3
```{r me-perc-atheist-us12}
# type your code for Question 8 here, and Knit
qnorm(0.975) * sqrt(atheist_us_por * (1 - atheist_us_por) / total_us)
```
<div id="exercise">
**Exercise**: Using the inference function, calculate confidence intervals for the proportion of atheists in 2012 in two other countries of your choice, and report the associated margins of error. Be sure to note whether the conditions for inference are met. It may be helpful to create new data sets for each of the two countries first, and then use these data sets in the `inference` function to construct the confidence intervals.
</div>
```{r me-perc-atheist-other-countries}
# type your code for the Exercise here, and Knit
German_2012 <- atheism %>%
filter(nationality == "Germany", year == "2012")
total_German <- German_2012 %>%
summarise(n())
total_atheist_German <- German_2012 %>%
filter(response == "atheist") %>%
summarise(n())
por_German_atheist <- total_atheist_German / total_German
por_German_atheist
SE <- sqrt(por_German_atheist * (1 - por_German_atheist) / total_German)
qnorm(0.975) * SE
c(por_German_atheist - qnorm(0.975) * SE, por_German_atheist + qnorm(0.975) * SE)
# Which is equivalent to:
inference( y = response, data = German_2012 , type = "ci", statistic = "proportion", success = "atheist", method = "theoretical")
Romania_2012 <- atheism %>%
filter(nationality == "Romania", year == "2012")
total_Romania <- Romania_2012 %>%
summarise(n())
total_atheist_Romania <- Romania_2012 %>%
filter(response == "atheist") %>%
summarise(n())
por_Romania_atheist <- total_atheist_Romania / total_Romania
por_Romania_atheist
SE <- sqrt(por_Romania_atheist * (1 - por_Romania_atheist) / total_Romania)
qnorm(0.975) * SE
c(por_Romania_atheist - qnorm(0.975) * SE, por_Romania_atheist + qnorm(0.975) * SE)
# Which is equivalent to:
inference( y = response, data = Romania_2012 , type = "ci", statistic = "proportion", success = "atheist", method = "theoretical")
```
## How does the proportion affect the margin of error?
Imagine you've set out to survey 1000 people on two questions: are you female? and are you left-handed? Since both of these sample proportions were calculated from the same sample size, they should have the same margin of error, right? Wrong! While the margin of error does change with sample size, it is also affected by the proportion.
Think back to the formula for the standard error: $SE = \sqrt{p(1-p)/n}$. This is then used in the formula for the margin of error for a 95% confidence interval: $ME = 1.96\times SE = 1.96\times\sqrt{p(1-p)/n}$. Since the population proportion $p$ is in this $ME$ formula, it should make sense that the margin of error is in some way dependent on the population proportion. We can visualize this relationship by creating a plot of $ME$ vs. $p$.
The first step is to make a vector `p` that is a sequence from $0$ to $1$ with each number separated by $0.01$. We can then create a vector of the margin of error (`me`) associated with each of these values of `p` using the familiar approximate formula ($ME = 1.96 \times SE$). Lastly, we plot the two vectors against each other to reveal their relationship.
```{r me-plot}
d <- data.frame(p <- seq(0, 1, 0.01))
n <- 1000
d <- d %>%
mutate(me = 1.96*sqrt(p*(1 - p)/n))
ggplot(d, aes(x = p, y = me)) +
geom_line()
```
9. Which of the following is false about the relationship between $p$ and $ME$.
<ol>
<li> The $ME$ reaches a minimum at $p = 0$. </li>
<li> The $ME$ reaches a minimum at $p = 1$. </li>
<li> The $ME$ is maximized when $p = 0.5$. </li>
<li> The most conservative estimate when calculating a confidence interval occurs when $p$ is set to 1. </li>
</ol>
ANSWER 4
The question of atheism was asked by WIN-Gallup International in a similar survey that was conducted in 2005. We assume here that sample sizes have remained the same. Table 4 on page 13 of the report summarizes survey results from 2005 and 2012 for 39 countries.
Answer the following two questions using the `inference` function. As always, write out the hypotheses for any tests you conduct and outline the status of the conditions for inference.
10. True / False: There is convincing evidence that Spain has seen a change in its atheism index between 2005 and 2012. <br><br> *Hint:* Create a new data set for respondents from Spain. Then use their responses as the first input on the `inference`, and use `year` as the grouping variable.
<ol>
<li> True </li>
<li> False </li>
</ol>
```{r spain-05-12}
# type your code for Question 10 here, and Knit
# H0 : p_Spain_atheist_2005 = p_Spain_atheist_2012
# HA : p_Spain_atheist_2005 /= p_Spain_atheist_2012
Spain_data <- atheism %>%
filter(nationality == "Spain")
Spain_data
total_2005 <- Spain_data %>%
filter(year == "2005") %>%
summarise(n())
total_2012 <- Spain_data %>%
filter(year == "2012") %>%
summarise(n())
total_atheist_spain_2005 <- Spain_data %>%
filter(year == "2005", response == "atheist") %>%
summarise(n())
total_atheist_spain_2012 <- Spain_data %>%
filter(year == "2012", response == "atheist") %>%
summarise(n())
p_hat_2005 <- total_atheist_spain_2005 / total_2005
p_hat_2012 <- total_atheist_spain_2012 / total_2012
SE <- sqrt((p_hat_2005 * (1-p_hat_2005) / total_2005) + (p_hat_2012 * (1-p_hat_2012) / total_2012))
Zvalue <- (p_hat_2005 - p_hat_2012 ) / SE
pnorm( 0.8477852 , lower.tail = FALSE) * 2
# This is equivalent to:
inference(y = response, x = year, data = Spain_data, type = "ht", statistic = "proportion", success = "atheist", method = "theoretical", null = 0, alternative = "twosided")
#Therefore we accept the null hypothesis and Spain has not changed
```
11. True / False: There is convincing evidence that the United States has seen a change in its atheism index between 2005 and 2012.
<ol>
<li> True </li>
<li> False </li>
</ol>
```{r us-05-12}
# type your code for Question 11 here, and Knit
US_data <- atheism %>%
filter(nationality == "United States")
inference(y = response, x = year, data = US_data, type = "ht", statistic = "proportion", success = "atheist", method = "theoretical", null = 0, alternative = "twosided")
# We reject the null
total_US_2005 <- US_data %>%
filter(year == "2005") %>%
summarise(n())
total_US_2012 <- US_data %>%
filter(year == "2012") %>%
summarise(n())
US_atheist_2005 <- US_data %>%
filter(year == "2005" , response == "atheist") %>%
summarise(n())
US_atheist_2012 <- US_data %>%
filter(year == "2012" , response == "atheist") %>%
summarise(n())
p_hat_US_atheist_2005 <- US_atheist_2005 / total_US_2005
p_hat_US_atheist_2012 <- US_atheist_2012 / total_US_2012
# H0 : p_2005 = p_2012
# HA: p_2005 /= p_2012
SE <- sqrt((p_hat_US_atheist_2005 * (1 - p_hat_US_atheist_2005) / total_US_2005) + (p_hat_US_atheist_2012 * (1 - p_hat_US_atheist_2012) / total_US_2012))
Z <- (p_hat_US_atheist_2012 - p_hat_US_atheist_2005) / SE
pnorm(5.279398, lower.tail = FALSE) * 2
```
12. If in fact there has been no change in the atheism index in the countries listed in Table 4, in how many of those countries would you expect to detect a change (at a significance level of 0.05) simply by chance? <br><br> *Hint:* Type 1 error.
<ol>
<li> 0 </li>
<li> 1 </li>
<li> 1.95 </li>
<li> 5 </li>
</ol>
```{r type1}
# type your code for Question 12 here, and Knit
```
13. Suppose you're hired by the local government to estimate the proportion of residents that attend a religious service on a weekly basis. According to the guidelines, the estimate must have a margin of error no greater than 1% with 95% confidence. You have no idea what to expect for $p$. How many people would you have to sample to ensure that you are within the guidelines? <br><br> *Hint:* Refer to your plot of the relationship between $p$ and margin of error. Do not use the data set to answer this question.
<ol>
<li> 2401 people </li>
<li> At least 2401 people </li>
<li> 9604 people </li>
<li> At least 9604 people </li>
</ol>
ANSWER 4
```{r sample-size}
# type your code for Question 13 here, and Knit
ME <- 0.01
# ME = qnorm(0.975) * sqrt ( p * (1-p) / n)
# To ensure that we are within guidline, we can put the worst p for ME ... which is 0.5
0.5 * 0.5 / (ME / qnorm(0.975)) ^ 2
```
<div id="license">
This is a product of OpenIntro that is released under a [Creative Commons
Attribution-ShareAlike 3.0 Unported](http://creativecommons.org/licenses/by-sa/3.0).
This lab was written for OpenIntro by Andrew Bray and Mine Çetinkaya-Rundel.
</div>