2 title: "Problem set 1: Worked solutions"
3 subtitle: "Statistics and statistical programming \nNorthwestern University \nMTS 525"
5 date: "September 28, 2020"
15 ```{r setup, include=FALSE}
16 knitr::opts_chunk$set(echo = TRUE)
19 ## PC 1: Access and describe a dataset provided in an R library
24 ## This first command can install the pacakge. I've commented it out here because it only needs to run once.
25 ## You can also install packages from the 'Packages' tab of the Rstudio interface.
27 ## install.packages("openintro")
39 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:
44 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.
46 The results of this call are actually sufficient to answer PC1.3 and PC1.4 below.
50 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:
60 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 ## just an example here:
67 ## lapply() is useful for doing this over all variables in a dataframe/tibble
72 For my example, I'll work with the `poverty` variable:
75 length(county$poverty)
76 min(county$poverty, na.rm=TRUE) ## That na.rm=TRUE part is crucial!
77 max(county$poverty, na.rm=TRUE)
78 mean(county$poverty, na.rm=TRUE) ## So many significant digits...
79 sd(county$poverty, na.rm=TRUE)
81 ## And here's a built-in command that covers many of these:
82 summary(county$poverty)
89 boxplot(county$poverty)
95 Because each row in the dataset corresponds to a county, the following will summarize the number of counties per state in the data
101 ## PC2. Working with a dataset from the web
106 set.seed(220920) ## A recent date.
107 sample(x=c(1:20), size=1)
109 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 I'll do this by pointing RStudio directly to the URL for the data using the `url()` and `load()` commands.
116 load(url("https://communitydata.science/~ads/teaching/2020/stats/data/week_03/group_03.RData"))
118 ls() # shows me what's available. The counties dataset is still hanging around.
123 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.
125 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 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)
139 var(d) ## variance. compare to the standard deviation
140 IQR(d) ## interquartile range
142 ## A handy Base-R command that does a bunch of these at once:
147 Graphing using R's built-in functions:
160 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)`).
162 Onwards to the new mean and standard deviation:
165 mean(d, na.rm=T) # R can understand "T" in place of TRUE
168 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?
173 d.log <- log1p(d) # Note: I use log1p() because some values are very close to zero
176 median(d.log, na.rm=T)
184 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:
187 ## if you haven't already you'll need to make sure ggplot2 is installed
188 ## install.packages("ggplot2")
191 p <- ggplot() + aes(d.log)
193 p + geom_boxplot(aes(x="", y=d.log))
195 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.
197 ## Statistical questions
201 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 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 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).