]> code.communitydata.science - stats_class_2020.git/blob - psets/pset1-worked_solution.rmd
posted version of pset1 worked solution
[stats_class_2020.git] / psets / pset1-worked_solution.rmd
1 ---
2 title: "Problem set 1: Worked solutions"
3 subtitle: "Statistics and statistical programming  \nNorthwestern University  \nMTS 525"
4 author: "Aaron Shaw"
5 date: "September 28, 2020"
6 output: 
7   html_document:
8     toc: true
9     toc_float:
10       collapsed: true
11       smooth_scroll: true
12     theme: readable
13   pdf_document:
14     toc: yes
15     toc_depth: '3'
16 ---
17
18 ```{r setup, include=FALSE}
19 knitr::opts_chunk$set(echo = TRUE)
20 ```
21
22 ## PC 1: Access and describe a dataset provided in an R library
23
24 ### PC1.1
25
26 ```{r}
27 ## This first command can install the pacakge. I've commented it out here because it only needs to run once. 
28 ## You can also install packages from the 'Packages' tab of the Rstudio interface.
29 ##
30 ## install.packages("openintro")  
31
32 library(openintro)
33
34 data("county")
35 ```
36
37 ### PC1.2
38
39 ```{r}
40 class(county)
41 ```
42 Notice that the results of that last call to `class()` produced something you might not have expected: three different values! This is because the OpenIntro authors have provided this dataset as something called a "tibble" (that's the `tbl_df` and `tbl` bits) which is basically a souped-up Tidyverse analogue to a Base-R dataframe. You can do some nice things with Tidyverse tibbles. For example, you can invoke them directly and not worry that R is going to print out a massive amonut of data at your console. The output also includes information about the dimensions and the types/classes of the columns/variables in the Tibble. Here's what it looks like:
43
44 ```{r}
45 county
46 ```
47 Notice that the Tibble refers to some numeric variables as "<dbl>" ("doubles") and others as "<int"> ("integers"). The latter maps to the colloquial idea of an integer. A "double" is a programming-language speak for a variable that takes non-integer numeric values. 
48
49 The results of this call are actually sufficient to answer PC1.3 and PC1.4 below.
50
51 ### PC1.3
52
53 If you didn't know or didn't realize that calling a Tibble directly answered this, here are some other ways to find the dimensions of a dataset:
54
55 ```{r}
56 dim(county)
57
58 nrow(county)
59 ncol(county)
60 ```
61
62 ### PC1.4
63 Again, some additional tools/approaches you might use to answer this if the Tibble method isn't available/known to you. Note that you can find out the class for any one variable easily with the `class()` command. Iterating this over the names of all the variables in a dataframe is feasible, but tedious and inefficient, so I provide a more concise method with `lapply()` below:
64 ```{r}
65 names(county)
66
67 ## just an example here:
68 class(county$poverty)
69
70 ## lapply() is useful for doing this over all variables in a dataframe/tibble
71 lapply(county, class)
72 ```
73 ### PC1.5
74
75 For my example, I'll work with the `poverty` variable:
76 ```{r}
77
78 length(county$poverty)
79 min(county$poverty, na.rm=TRUE) ## That na.rm=TRUE part is crucial!
80 max(county$poverty, na.rm=TRUE)
81 mean(county$poverty, na.rm=TRUE) ## So many significant digits... 
82 sd(county$poverty, na.rm=TRUE)
83
84 ## And here's a built-in command that covers many of these:
85 summary(county$poverty)
86 ```
87 ### PC1.6
88
89 ```{r}
90 hist(county$poverty)
91
92 boxplot(county$poverty)
93 ```
94
95
96 ### PC1.7
97
98 Because each row in the dataset corresponds to a county, the following will summarize the number of counties per state in the data
99 ```{r}
100 table(county$state)
101 ```
102
103
104 ## PC2. Working with a dataset from the web
105
106 ### PC2.1
107
108 ```{r}
109 set.seed(220920) ## A recent date. 
110 sample(x=c(1:20), size=1)
111 ```
112 My dataset number for the rest of this worked solution to the programming challenge is 3. That said, the code should work if you substitute an appropriate group number into the url below.
113
114 ### PC2.2
115
116 I'll do this by pointing RStudio directly to the URL for the data using the `url()` and `load()` commands.
117
118 ```{r}
119 load(url("https://communitydata.science/~ads/teaching/2020/stats/data/week_03/group_03.RData"))
120
121 ls() # shows me what's available. The counties dataset is still hanging around.
122
123 head(d)
124 ```
125
126 Note: If you downloaded the file, you'll need to point R's `load()` command at the correct file location on your machine. RStudio can be...picky about this sort of thing.
127
128 Also, a clarifying point: if you're compiling your own RMarkdown scripts, you will need to load the dataset explicitly (not just open the file with RStudio). When RMarkdown tries to "knit" the .Rmd file into HTML or whatever, it is as if you are running the entire contents of the .Rmd script in an entirely new RStudio environment. This means if you don't load something explicitly within the .Rmd script RStudio will not know where to find it.
129
130 ### PC2.3
131
132 I'll do all the ones I asked for as well as some I didn't (just so you have an example what the commands look like)
133
134 ```{r}
135 min(d)
136 max(d)
137 mean(d)
138 sd(d)
139
140 ## extras
141 median(d)
142 var(d) ## variance. compare to the standard deviation
143 IQR(d) ## interquartile range
144
145 ## A handy Base-R command that does a bunch of these at once:
146 summary(d)
147 ```
148 ### PC2.4
149
150 Graphing using R's built-in functions:
151 ```{r}
152
153 hist(d)
154 boxplot(d)
155
156 ```
157
158 ### PC2.5
159
160 ```{r}
161 d[d < 0] <- NA
162 ```
163 Fwiw, I want to point out that this last line of code is a little "fast and loose." I have reused my original variable name when I recode the negative values to `NA`. This means that my copy of `d` has been changed and the only way I can restore it is by reading in the raw data again (which would, in turn, overwrite my recoded copy). It is often a good idea to check your work after recoding. You could do that here by "stashing" the original variable in a new object/name (e.g., run something like `d.orig <- d` before running the line above). Then after you've recoded the negative values, you could run whatever tests/comparisons you like to make sure the recoding is correct before deleting the original data (which can be done with `rm(d.orig)`). 
164
165 Onwards to the new mean and standard deviation:
166
167 ```{r}
168 mean(d, na.rm=T) # R can understand "T" in place of TRUE
169 sd(d, na.rm=T)
170 ```
171 Both values here are larger than before I removed my negative values. This is pretty intuitive in the case of the mean, but maybe less so with the standard deviation since the range of the values in the recoded variable is smaller. Can you explain how the standard deviation would increase? 
172
173 ### PC2.6
174
175 ```{r}
176 d.log <- log1p(d) # Note: I use log1p() because some values are very close to zero
177
178 mean(d.log, na.rm=T)
179 median(d.log, na.rm=T)
180 sd(d.log, na.rm=T)
181
182 hist(d.log)
183 boxplot(d.log)
184
185 ```
186
187 Next week, I will introduce the `ggplot2` package in the R tutorial. For now, I'll reproduce the historgram and boxplot I made above in ggplot2 and leave these examples here for future reference. Graphing a single vector in ggplot2 is a bit weird, so this looks a little different than the examples from the R lecture:
188
189 ```{r}
190 ## if you haven't already you'll need to make sure ggplot2 is installed
191 ## install.packages("ggplot2")
192
193 library(ggplot2)
194 p <- ggplot() + aes(d.log)
195 p + geom_histogram()
196 p + geom_boxplot(aes(x="", y=d.log))
197 ```
198 Note that ggplot2 generates a warning about 5 "non-fininte values." In this case, that is due to the 5 `NA` values I created when I recoded the negatives, so I don't need to worry about the warning.
199
200 ## Statistical questions
201
202 ### SQ1
203
204 A compelling answer to this depends on the variable you chose. For the one I looked at in my example code (`poverty`) the data is somewhat right skewed, but not much. In this case, the mean and standard deviation should represent the central tendency and spread of the variable pretty well. If your variable was different (e.g., one of the population or income measures, it would probably be good to also examine and report the median and interquartile range. See `OpenIntro` chapter 2 for more on distinctions/reasons behind this.
205
206 ### SQ2
207
208 Definitely not. The data is very skewed with a long (positive) tail, suggesting that median and interquartile range would be better measures to report.
209
210 ### SQ3  
211
212 The cleaned and log-transformed version of the variable has no negative values and is far less right-skewed than the original. You should absolutely prefer the cleaned variable with no negative values since they resulted from a coding error (see the text of PC2.5). However, a preference for the log-transformed or untransformed variable likely depends on the situation. It's almost always good to report descriptive statistics for "raw," untransformed versions of your variables. However, you might prefer the log-transformed version for developing a stronger set of intuitions about your data, comparing with prior work that uses log-transformed versions of a similar measure, or conducting certain statistical tests (we'll talk more about this later in the course).

Community Data Science Collective || Want to submit a patch?