]> code.communitydata.science - stats_class_2020.git/blob - r_tutorials/w01-R_tutorial.rmd
renaming to remove arbitrary capitalization
[stats_class_2020.git] / r_tutorials / w01-R_tutorial.rmd
1 ---
2 title: "Week 1 R Tutorial"
3 author: "Aaron Shaw"
4 date: "September 15, 2020"
5 output:
6   html_document:
7     toc: yes
8     toc_depth: 2
9     theme: readable
10   pdf_document:
11     toc: yes
12     toc_depth: '2'
13 subtitle: "Statistics and Statistical Programming  \nNorthwestern University  \nMTS
14   525"
15 ---
16
17 ```{r setup, include=FALSE}
18 knitr::opts_chunk$set(echo = TRUE)
19 ```
20
21
22 # Screencast #1
23 ## Very brief introduction to R (and R Studio and R Markdown)
24
25 If this is your first foray into R (or just your latest attempt), welcome! I hope this introduction helps you get started. 
26
27 This file accompanies a screencast. The idea is that you can watch the screencast with RStudio and the file open on your own machine. You can read the compiled file as an HTML or PDF document and interact with it more directly by opening the accompanying .Rmd (RMarkdown) file in R Studio.
28
29 We'll begin with a few basics. What is R? What is R Studio? What is the R Console? What is R Markdown? After that (in the second screencast), we'll move on to performing some basic operations that you'll need to understand to actually use R to perform statistical programming.
30
31 ## What is R?
32
33 R is a free software environment and programming language for statistical computing. At it's core, it's a very flexible system that you can use to conduct any kind of statistical computing you (or anyone else) can imagine. People may say "R" to refer to the language and the software environment interchangeably. You can read more about R on the [R project home page](https://www.r-project.org/about.html).
34
35 ## What is R Studio?
36
37 [R Studio](https://www.rstudio.com) is an "integrated development environment" (IDE) that you can use with R. In other words, it's an application built to make it relatively easy to conduct statistical analysis, manage datasets, generate plots, and generally interact with R in a whole variety of ways.
38
39 R Studio has a bunch of options that you can use to adjust the look, feel, and organization of the interface. You can find them under the 'Tools' menu and 'Global Options'.
40
41 R Studio also has a number of very, very helpful keyboard shortcuts. Personally, I love keyboard shortcuts and I find that they vastly improve my experience using R Studio. If you want to learn the keyboard shortcuts, print out a copy of a cheatsheet [like this](https://github.com/rstudio/cheatsheets/raw/master/rstudio-ide.pdf) and make sure it's handy any time you even think about using R Studio. You'll improve quickly.
42
43 The most important keyboard shortcut when you're using R Studio is probably 'CTRL-Enter.' It lets you send a command from the scripting window to the R console.
44
45 ## What is the R Console?
46
47 If you're have opened RStudio, you should see a window labeled "Console." This window allows you to enter direct commands to R. You can type these commands after the little sideways angle-bracket symbol ('>') or send them to the console from a script or notebook file. I will demonstrate how I do both of these things in the screencast.
48
49 The important thing to know about the R Console is that when you type anything (a 'statement') after the sideways angle-bracket and press 'Enter' R will try to evaluate the statement and "do" whatever it says. If the console cannot evaluate the statement successfully, it will generate an error.
50
51 ## What is RMarkdown?
52
53 RMarkdown is a markup language that you can use to create documents that combine snippets of text and (evaluated) R code. This file was created as an RMarkdown document. You can use RMarkdown to compile documents in many formats, including HTML, PDF, or MS Word documents. For more details on using RMarkdown see <http://rmarkdown.rstudio.com> where you can also access a series of dedicated [tutorials](https://rmarkdown.rstudio.com/lesson-1.html). 
54
55 You can think of RMarkdown files as "notebooks" where you can write, execute, and compile a combination of text and R code that can then be "knitted" together. Indeed, this is exactly what RStudio does when you click the **Knit** button above an open RMarkdown (.Rmd) file. Clicking **Knit** (or executing the corresponding keyboard shortcut) will produce a document that includes both the text content as well as the output of any embedded R code "chunks" within the document. An embedded R code chunk looks like this:
56
57 ```{r cars}
58 summary(cars)
59 ```
60
61 That chunk calls a built-in function 'summary' to provide information about a built-in dataset called 'cars'. R has many built-in functions and a few built-in datasets. We'll come back to them later. For now, the point is that you can see how RMarkdown integrates a snippet of code and the results of executing that code right into the flow of the text.
62
63 Embedding a new code chunk is easy. There is an 'Insert chunk' option in the 'Code' menu as well as an 'Insert' dropdown at the top of the .Rmd window. You can also use the keyboard shortcut (recommended! It's CTRL-ALT-i for Windows/Linux/Chrome users).
64
65 RMarkdown also lets you format text in a variety of ways including *italics* and **bold**.[^1] 
66
67 RMarkdown is not required for this course, but I strongly recommend that you invest the effort to learn to work in something like RMarkdown (other alternatives include Jupyter Notebooks or LaTeX) to complete your problem sets. The results will be clean, easy-to-read files that can integrate R code, analysis output, and graphics.
68
69 [^1]: It even does footnotes!
70
71 ### Including Plots in R Markdown
72
73 You can also embed plots, for example here's a plot of another one of R's built-in datasets containing data on the relation between temperature in degrees Celsius and vapor pressure of mercury in millimeters (of mercury).:
74
75
76 ```{r pressure, echo=FALSE}
77 plot(pressure)
78 ```
79
80 Note that the R code that generated the plot didn't show up this time. That's because I included an `echo = FALSE` parameter at the beginning of the code chunk (open up the .Rmd file to see what this looks like and try changing it the `echo = TRUE`). It is sometimes helpful to run code chunks without printing them.
81
82 ## Some other basics of R Studio
83
84 R Studio is being very actively developed and has many features that I don't know much/anything about. You can learn a **lot** more on the R Studio site and online (more on that in a moment). For now, I want to make sure you know how to do a few other things that will make it possible to complete your assignments for my class.
85
86 ### Setting preferences and options
87
88 The appearance and some features of R studio can be customized "globally" (across all projects) through the 'Global options' item in the 'Tools' menu. For example, I prefer a darker editor theme that feels more relaxing on my eyes.
89
90 ### Working with projects
91
92 An R Studio 'project' is a bundle of data, code, figures, output, and more that you want to keep bundled together. A project might contain multiple data files or notebooks. It also might contain other material such as a README file (documentation), supplementary materials, or even a finished paper. For the purposes of class, you may want to treat each problem set or assignment as an R Studio project.
93
94 R Studio projects are saved as '.Rproj' files accompanied by whatever else the project may entail. You can open them with R Studio and/or create new ones from the 'File' menu (select 'New Project'). Note that R studio can have multiple scripts and/or R Markdown files open, but seems to only be able to have one project open at a time.
95
96 ### Creating and saving a new R Markdown script
97
98 Creating new R Markdown scripts is also very straightforward in R Studio. From the 'File' menu, select 'New File' and 'R Markdown'. This will let you define some key attributes of the new file and automatically populate the .Rmd with some basic information.
99
100 ### Getting help
101
102 There are many, many ways to get help figuring out how to do things in R, R Studio, and R Markdown. I'll talk more about getting help with R functions in the second Screencast, but for now you should make sure you also have some idea of where/how to look things up when you have questions about R Studio or R Markdown. For example, try out the 'Help' menu items and identify some of the cheatsheets (like the one I mentioned earlier) that you think you might want to have around while you're learning to use these tools. The R Studio website links to several other resources and tutorials that you might find useful. [StackOverflow](https://www.stackoverflow.com) also has extensive Q&A activity for questions about R, R Studio, Markdown, and related topics. 
103
104
105
106 \newpage
107
108 # Screencast #2
109 ## Basics of R
110
111 This second screencast focuses on building basic skills with R. It can/will be far more interactive. The rest of the R Markdown script is intentionally short and is basically just an outline of the topics that will be covered. Please run these commands and experiment with R yourself in parallel as you watch/listen. 
112
113 ## Using R as a calculator
114
115 R is a very fast calculator. You can enter simple arithmetic operations (addition, subtraction, multiplication, division, exponentiation) directly into the console or via your scripts, e.g.:
116
117
118 ```{r}
119 2 + 2
120 6/3
121 10^5
122 ```
123
124 Try entering some others at the console yourself.
125
126 ## Variables
127
128 In R, you can use variables to do many things. The basic idea is that a variable allows you to 'assign' a value or set of values to a name. You indicate assignment by typing `<-` (keyboard shortcut: 'Alt--') or `=`. Here's an example:
129
130 ```{r}
131 x <- 2
132 x
133 ```
134
135 In the first line, I assigned a value of '2' to be called 'x'. In the second line, I just type 'x', which tells R to print the value for x. Surprise, surprise, it prints '2'. (More on why it also prints `[1]` in a moment...)
136
137 Try this out yourself at the R console. Then try assigning another value to 'x' and ask R to print x again. 
138  
139 For the most part, you can assign any value or set of values to any variable name and you can then use the variable name instead of the value(s):
140
141 ```{r}
142 cups.of.coffee <- 3
143 cups.of.coffee + 1
144 cups.of.coffee*3
145 ```
146
147 Some variable names and words are 'special', however, in that R has pre-assigned values to them or pre-assigned functions. We will encounter many of these. For one example of a pre-assigned variable, try typing `pi` at the console and press 'Enter'.
148
149 One other special value a variable may take is `NA` (no quotes!) which means it is missing. If a value is missing, you may not be able to do mathematical operations with it:
150
151 ```{r}
152 cups.of.coffee <- NA
153 cups.of.coffee-1
154 ```
155
156 ## Types (also known as classes)
157
158 Every variable has a 'type' or 'class'. For example, we've already created a few variables which are 'numeric'. These can be whole integers or have decimals. If you ever want to know what a variable's type is, you can ask R to tell you using the `class()` function like this: 
159
160 ```{r}
161 class(x)
162 ```
163
164 We'll come back to functions in a moment. In the meantime, other important types of variables are are 'characters' and 'logical':
165
166 ```{r}
167 my.name <- "Aaron"
168 class(my.name)
169 my.answer <- TRUE ## Note the capitalization!
170 class(my.answer)
171 ```
172
173 It is often important to know what class a variable is because R lets you perform some operations on certain kinds of variables, but not on others.
174
175 ## Functions
176
177 In R, you use functions to do just about everything (e.g., inquire about the class or type of a variable as we did above). Every function takes some input (called an argument) usually in parentheses and provides some output (sometimes called the return value). Some functions take multiple inputs and return multiple outputs. You can also write your own functions and edit existing functions. This is part of what makes R so powerful and flexible.
178
179 Arguably the most important function is `help()`. The help function will retrieve the documentation for any function. To learn more about help, try entering `help(help)` at the console.
180
181 Another useful function allows you to delete a variable: `rm()` or `remove()`. Try creating a variable and removing it.
182
183 There are many built in functions. Some are common mathematical operations like `sqrt()`, `log()`, or `log1p()`. Others help you manage your workspace like `ls()`. 
184
185 Check your reference card for many, many more examples.
186
187 ## Vectors
188
189 You can think of a vector as a set of things that are all the same type. In R, all variables are vectors even though they may have just one thing in them! That's why the R Console prints out `[1]` next to the value of a variable with just one value:
190
191 ```{r}
192 my.name
193 ```
194
195 You can make vectors with a special function `c()`:
196
197 ```{r}
198 ages <- c(36, 50, 38)
199 ages
200
201 ```
202 Vectors can be of any type but they can have only one type: 
203 ```{r}
204 class(ages)
205 painters <- c("frida", "diego", "daniel")
206 class(painters)
207 ```
208
209 If you mix types vectors together, they will be "coerced" to a single type. The results be surprising (and sometimes annoying).
210
211 ```{r}
212 class(c(ages, painters)) ## Notice that you can "nest" functions within each other.
213 ```
214 ### Indexing
215
216 You can index the elements in a vector using square brackets and a number like this:
217
218 ```{r}
219 painters[2]
220 ```
221 You can also use indexing to refer to multiple elements in a vector
222 ```{r}
223 painters[2:3] ## A sequence of the second and third elements
224 ```
225 You can even assign new values to an item (or add items) in a vector using indexing:
226
227 ```{r}
228 ages[2] <- 52
229 ages
230 ```
231
232 ### Recycling
233
234 Mathematical operations are "recycled" when applied to a vector. R just performs the same operation on each item in the vector and gives you the output:
235
236 ```{r}
237 ages*2
238 ages/2
239 ```
240
241 ### Naming items
242
243 You can apply a name to any item in a vector
244 ```{r}
245 names(ages)
246 names(ages) <- c("Wilma", "Fred", "Barney")
247 names(ages)
248 ```
249 Now you can index into 'ages' using the name of each item:
250 ```{r}
251 ages["Barney"]
252 ```
253
254 ### Working with vectors with multiple elements
255
256 Some functions are very handy for working with vectors that have multiple elements:
257
258 ```{r}
259 length(ages)
260 sum(ages)
261 mean(ages)
262 sd(ages) ## Standard deviation. More on that later.
263 sort(ages)
264 range(ages)
265 summary(ages)
266 table(ages)
267 ```
268
269 You can also construct new vectors by performing logical comparisons on an existing vector:
270
271 ```{r}
272 ages < 39
273 ages != 38
274
275 painters == "Diego"
276 painters == "diego"
277 painters != "frida"
278 ```
279
280 This is very useful for indexing and recoding a variable. In this case I'll use the built-in variable 'rivers' which is the lengths in miles of 141 major North American rivers (type `help(rivers)` to learn more) :
281
282 ```{r}
283 rivers
284 head(rivers) ## 'head()' shows you the first five values of a vector
285 rivers < 300 ## Recycles the comparison and returns TRUE or FALSE for each river
286 rivers[rivers < 300] ## A subset of the data
287
288 little.rivers <- rivers[rivers < 300]
289 big.rivers <- rivers; big.rivers[big.rivers < 300] <- NA ## Two commands, one line. Recodes the short rivers as 'Missing'
290 ```
291
292 ## Basic plotting and visualizations
293
294 Visualizations can help you explore data and interpret results. Use them often!
295
296 ```{r}
297 table(rivers>300)
298 hist(rivers)
299 boxplot(rivers)
300 ```
301
302
303 ## Packages 
304
305 By default, R has many built-in functions and example datasets. However, many people have extended R by creating additional functions. Often these additional functions are collected together and distributed as "packages" or "libraries" that may also include additional datasets. Rstudio gives you a couple of ways to work with these. The traditional method is via the following commands 
306
307 ```{r eval=FALSE}
308
309 install.packages("UsingR") ## note the quotation marks. This package accompanies the Verzani book.
310 install.packages("openintro") ## This package goes along with our textbook.
311
312 ## Then you can load the package this way:
313 library(UsingR) ##  No quotes!
314 library(openintro)
315 ```
316 Run these commands on your system. Use the 'Packages' tab to explore the documentation of the functions and datasets available through the `openintro` package.
317
318 Note that I have told R not to evaluate this last chunk of code because it generates a bunch of output and you only need to install any given package once. To skip evaluating a code chunk you can include the `eval=FALSE` in the header to that chunk in your R Markdown file. This tells R not to execute the code when it knits the file. Take a look at the .Rmd file to learn more.
319
320 ## Loading datasets
321
322 Often datasets will be located online or locally on your computer and you'll want to load them directly. For '.Rdata' files you can do this using the `load()` command. For others you may want to use commands like `read.csv()`, `read.table()`, or `read.foreign()` (that last one requires the 'foreign' package, so you'll need to load it first). RStudio also has a drop-down menu item ('File' → 'Import dataset') that can help you load a local file.
323
324 ## Environment and History
325
326 By default, R Studio allows you to see all the variables or 'objects' currently available to you in a particular session. Find the window/tab called "Environment" and take a look at what's there.
327
328 There's another tab (likely in the same window) called "History" that contains all the commands you have run in the current session. This can be super helpful when you're trying to piece together what you did a few moments ago or why that command you just ran worked and the one you tried a before did not.
329
330 ## Getting help
331
332 As mentioned earlier, the `help()` command is your friend. RStudio also has a 'Help' tab in one of the default windows. You can also use the RStudio cheatsheets, StackOverflow, the Verzani textbook, the [Quick-R tutorials](https://www.statmethods.net/index.html), and/or many, many other resources on the internet, including the [rseek search engine](https://rseek.org/) (which just searches the web for R-related resources).

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