2 title: "Problem set 5: Worked solutions"
3 subtitle: "Statistics and statistical programming \nNorthwestern University \nMTS 525"
4 author: "Aaron Shaw (with Jeremy Foote)"
5 date: "October 26, 2020"
22 ```{r setup, include=FALSE}
23 knitr::opts_chunk$set(echo = TRUE, message=FALSE, tidy='styler')
26 # Programming Challenges
29 You had the option of downloading the dataset in several formats, including a Stata 13 ".dta" file. For demonstration purposes, I'll use that proprietary format here. I also uploaded a copy of the dataset to the course website for pedagogical purposes (so you can replicate my code here on your own machine).
31 There are a few ways to import data from Stata 13 files. One involves using the appropriately named `readstata13` package. Another uses the `haven` package (more of a general purpose tool for importing data from binary/proprietary formats). I'll go with the `read_dta()` command from `haven` here because it works better with importing from a URL.
36 df <- read_dta(url('https://communitydata.science/~ads/teaching/2020/stats/data/week_07/Halloween2012-2014-2015_PLOS.dta'))
39 ## PC2. Explore and cleanup
46 There are a few noteable things about the dataset. One is the `neob`, which the codebook says means "not equal to obama"; in other words, it's the converse of the `obama` column. The `treat_year` column is a unique index of the `obama` column and the `year` column. See the codebook for more information. Happily, we only need to use the first two columns for now.
48 I'll drop everything else and convert those two columns into logical vectors here using a couple of tidyverse `dplyr` commands:
54 select(obama, fruit) %>%
56 obama = as.logical(obama),
57 fruit = as.logical(fruit)
64 ## PC3. Summarize key variables
65 I'll run summary again and then make my contingency table.
70 obama.tbl <- table(took_fruit=df$fruit, saw_flotus=df$obama)
75 ## PC4. Test for differences between groups
76 So, the test we want to conduct here focuses on the difference between the proportion of the two groups (those shown a picture of Michelle Obama vs those not shown a picture of Michelle Obama) who took fruit vs. candy. Labeling the difference in proportions as $\Delta_{fruit}$, the comparison can be constructed around the following (two-sided) hypothesis test
78 $$ H_0:~\Delta_{fruit} = 0$$
79 $$ H_A:~\Delta_{fruit} \neq 0$$
80 As discussed at length in *OpenIntro* Chapter 6, a great way to determine if two groups are independent (in terms of proportions or counts) is a $\chi^2$ test.
82 Are the conditions for a valid test met? It seems so, since there are many observations in each cell of the table being compared and the observations appear to have been collected in a way that ensures independence.
84 The $\chi^2$ test is implemented as `chisq.test()` in R. Since it's a 2x2 comparison, we can also test for a difference in proportions using the `prop.test()` function. Let's do both.
86 ```{r hypothesis tests}
92 Notice that both functions report identical $\chi^2$ test results and p-values. Did you expect this based on the *OpenIntro* reading?
94 Recall that if you want to double-check that p-value, you can also calculate it "by-hand" using the `pchisq()` function:
95 ```{r p-value by hand}
96 pchisq(1.8637, df=1, lower.tail=FALSE)
99 We'll discuss the interpretation of these results in our class session this week.
101 ## PC5. Replicate a figure
103 In order to replicate the top panel of Figure 1, we'll first want to calculate the proportion and standard error for fruit-takers in the treatment and control groups. These can be calculated individually or using a function (guess which one we'll document here). Also, note that I'm going to use the `complete.cases()` function to eliminate the missing items for the sake of simplicity.
105 ```{r calc proportions and se}
106 df <- df[complete.cases(df),]
108 prop.se = function(values){# Takes in a vector of T/F values
110 prop = mean(as.numeric(values))
111 se = sqrt(prop * (1-prop)/N) ## textbook formula for SE of a proportion
115 prop.se(df$fruit[df$obama])
116 prop.se(df$fruit[!df$obama])
120 In order to graph that it will help to convert the results into a data frame with clearly-labeled variable names and values:
121 ```{r bind up proportions and se}
122 prop.and.se <- data.frame(
124 prop.se(df$fruit[df$obama]),
125 prop.se(df$fruit[!df$obama])
129 names(prop.and.se) <- c("proportion", "se")
130 prop.and.se$obama <- c(TRUE, FALSE)
134 Now we can start to build a visualization
136 ## library(ggplot2) ## already imported w the tidyverse
138 p <- ggplot(prop.and.se, aes(x=obama,y=proportion)) +
139 geom_point(aes(color=obama), size=5)
145 Looking pretty good. Let's go ahead and add some error bars:
147 p + geom_errorbar(aes(ymin=proportion - 1.96 * se, # Add error bars
148 ymax=proportion + 1.96 * se))
151 Now let's clean up those error bars a bit...
152 ```{r better error bars}
153 p1 <- p + geom_errorbar(aes(ymin=proportion - 1.96 * se,
154 ymax=proportion + 1.96 * se,
155 width=0, # Remove the whiskers
156 color=obama),size=1.1) # Make bars thicker and apply color
161 Great! Now I can style it a bit more by flipping the plot on it's side with `coord_flip()`, adding a theme, converting it to grayscale, and fixing up my axes a bit:
164 p1 + coord_flip() + # Flip the chart
165 theme_light() + # Change the theme (theme_minimal is also nice)
166 scale_color_manual(values = c('gray','black'), guide=F) + # Change the colors
167 ylim(0,.5) + # Change the y axis to go from 0 to .5
168 ylab('Proportion choosing fruit') + # Add labels
169 xlab('Picture shown was Michelle Obama')
175 ## PC6. Export a table
177 Here's one way to export our table, using `write.csv()` (and have commented it out, so you can run locally and determine where the exported file goes).
178 ```{r simple csv export}
179 ## uncomment to generate exported file
180 ## write.csv(obama.tbl, file = 'crosstabs.csv')
182 We can make sure it worked by importing it (again, commented out here):
183 ```{r test simple export}
184 ## read.csv('crosstabs.csv')
186 We lost some information, because the `table()` function doesn't save column names. Another way to do this would be to change it into a dataframe first, like this:
187 ```{r convert to dataframe}
188 data.frame(obama.tbl)
190 and then save that dataframe. Note that you can drop the rownames when importing (or exporting)
191 ```{r export dataframe}
192 ## write.csv(data.frame(obama.tbl), file = 'crosstabs.csv', row.names = FALSE)
194 ## read.csv('crosstabs.csv')
196 That's formatted a little bit funny, but it's still usable.
198 You could also use the `xtable` package to do this. The package has many functions to customize table outputs in several formats. A relatively simple way to generate an html table looks like this:
199 ```{r xtable example}
201 print(xtable(obama.tbl), type="html")
204 You can export by assigning the html to an object and saving. I've commented it out here so you can choose whether/where to create the file:
206 ## uncomment to generate file output
208 ## print(xtable(obama.tbl), type="html", file="example_table.html")
211 You should be able to open that file in a web-browser.
213 There is a lot of documentation and examples online to help you customize as you see fit. If you're really excited about exporting tables, you might also take a look at the `tables` package, which has some nice export options.
215 # Empirical paper questions
216 ## EQ1. LilyPad Arduino users
218 a) The unit of analysis is the customer. The dependent variable is the type of board purchased and the independent variable is gender. Males, females, and unknown gender customers are being compared. This is a two-way test.
220 b) For this type of comparison statistical tests help to give (or take away) confidence in any observed differences in counts or proportions across categories. Choosing a statistical test is based on the question that you want to answer and the type of data that you have available to answer it. For example, if this were continuous numeric data (e.g., the amount of money spent on electronics for men and women) then we would want a different to compare those distributions. Given that the test compares counts (or proportions) a $\chi^2$ test for independence is appropriate.
222 c) The null hypothesis ($H_0$) is that the board purchased is independent of the gender of the customer. The alternative hypothesis ($H_A$) is that board purchase choice is dependent on gender.
224 d) A $\chi^2$ test results indicate that board purchase behavior differs by gender ($p~\leq~0.05$). This difference is convincing, but it does directly not tell us what the authors set out to understand, which is the difference between men and women (the test as-implemented might have identified a significant difference in the number of unknown gender customers across board types!). Many of these concerns are addressed in the text and with additional tests, giving increased confidence in the observed differences.
227 ## EQ2. Two blogospheres
229 a) The data are counts for two categorical variables and the procedure used was a $\chi^2$ test. The null hypothesis is that blog governance (by one person or more than one person) is independent of whether the blog was on the left or the right ideologically.
231 b) One way to approach this focuses on the credibility of the null hypothesis. A null of equality/independence in this case seems like it might be a bit of a stretch since there are potentially so many factors involved in determining site governance. If we accept that the null hypothesis of no difference across the two groups is compelling, it seems like it could be surprising to see these results in a world where ideological orientation and blog governance have no relationship. In this respect, it makes sense to believe that there is some relationship of dependence. A closer reading of the paper suggests a different reason to be skeptical: the way that the measure of blog governance groups the data into categories. The authors could have grouped them differently (e.g., 1-2 people, 3-4 people, and 5+ people). If the decision on how to group was made after seeing the data or if the observed result depends on the choice of grouping, then we have good reason to be skeptical.
233 c) We can do this in R.
235 ```{r replicate Shaw and Benkler tabular}
237 ## First we create the dataframe
238 df = data.frame(Governance=c('Individual','Multiple', 'Individual','Multiple'),
239 Ideology = c('Left','Left','Right','Right'),
240 Count = c(13,51,27,38))
244 ## We can make sure it's the same by testing the Chi-squared
245 chisq.test(matrix(df$Count, nrow=2))
247 ## We can convert that into proportions several ways.
248 proportions(matrix(df$Count, nrow=2), margin =2)
250 ## Here's one using tidyverse code that yields more readable results:
251 percentage_data <- df %>%
252 group_by(Ideology) %>%
253 summarize(individual_ratio = sum(Count[Governance=='Individual']) / sum(Count),
254 ideology_count = sum(Count))
259 And here we go with a figure using the `geom_bar()` layer in `ggplot2`. Note that by calling `stat=\'identity\'', we tell ggplot to vizualize the provided counts (instead of trying to summarize the data further):
260 ```{r replicate Shaw and Benkler figure 2}
261 shaw_benkler_plot = percentage_data %>%
262 ggplot(aes(x=Ideology, y=individual_ratio * 100)) +
263 geom_bar(stat='identity', aes(fill=c('red','blue')), show.legend=F) +
264 ylab('Percentage of Blogs') + theme_minimal()
269 If we want to add error bars, we need to calculate them (Note that ggplot could do this for us if we had raw data - what a helpful reminder to always share your data!).
271 For our purposes here, you might decide to use confidence intervals or standard errors (both seem like reasonable choices as long as you label them). Either way, ggplot has a `geom_errorbar` layer that is very useful.
273 Remember that for a binomial distribution (we can consider individual/non-individual as binomial), confidence intervals are
274 $\hat{p} \pm z^* \sqrt{\frac{\hat{p}~(1-\hat{p})}{n}}$ and we can approximate $z^*~=~1.96$ for a 95% confidence interval.
276 ```{r add CIs to Shaw and Benkler Fig 2}
277 ci_95 = 1.96 * sqrt(percentage_data$individual_ratio * (1 - percentage_data$individual_ratio)/percentage_data$ideology_count)
279 shaw_benkler_plot + geom_errorbar(aes(ymin=(individual_ratio-ci_95)*100, ymax=(individual_ratio + ci_95)*100),
286 The 95% confidence intervals overlap in this case, indicating that the true population proportions may not be as far apart as our point estimates suggest. Note that this is not the same as the hypothesis test (illustrating one of Reinhart's points).
288 d) On the one hand, we don't need to worry about the base rate fallacy because the sizes of both groups are about the same and the paper does not abuse the evidence too egregiously. The base rate fallacy would likely come into play, however, in the ways that the results are (mis)represented. For example, you might imagine some news coverage looking at these results and claiming something (totally wrong!) like "study finds right wing blogs more than twice as likely to be solo affairs." This is taking a relationship between the sample proportions ($\hat{p}$ in the language of our textbook) and converting that into a statement about the relationship between population proportions ($p$). That would be a bit of a mess (and absolutely characterizes the news coverage that did follow the study).
290 Another way in which the base rate fallacy could play a role in this paper, however, concerns the presence of multiple comparisons. The authors conducted numerous statistical tests (indeed, one of the authors seems to recall that some of the tests were not even reported in the paper <gasp!>) and they make no effort to address the baseline probability of false positives.
292 In any case, the point here is that the statistical tests reported in the paper may not mean exactly what the authors said they did in the context of the publication. That may or may not change the validity of the results, but it should inspire us all to do better statistical analysis.