-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathUntitled.qmd
1425 lines (863 loc) · 37.5 KB
/
Untitled.qmd
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: |
| Microeconometrics
| Week 1 - Introduction to R
author:
|
| Joshua D. Merfeld
| KDI School
date: "`r Sys.Date()`"
# Output type and options (no TOC and yes fig captions)
output:
beamer_presentation:
theme: Montpellier
classoption: "aspectratio=169"
# This includes latex arguments
header-includes:
- \AtBeginDocument{\title[Week 1 - Introduction to R]{Microeconometrics \\ Week 1 - Introduction to R}}
- \input{header.tex}
---
```{r setup, include=FALSE}
def.chunk.hook <- knitr::knit_hooks$get("chunk")
knitr::knit_hooks$set(chunk = function(x, options) {
x <- def.chunk.hook(x, options)
#ifelse(options$size != "a", paste0("\n \\", "tiny","\n\n", x, "\n\n \\normalsize"), x)
ifelse(options$size != "normalsize", paste0("\n \\", options$size,"\n\n", x, "\n\n \\normalsize"), x)
})
knitr::opts_chunk$set(echo = FALSE, dev = "png") # NOTE: switched to png instead of pdf to decrease size of the resulting pdf
library(tidyverse)
library(nycflights13)
library(kableExtra)
# read in the data
data <- read_csv("data.csv")
```
# Introduction
## Goal for today
\vfill
- The goal for today is to give you a brief introduction to R and R Markdown
\vfill
- We will be using two small datasets to get you familiar with the program
- Class website
\vfill
- A note: if you are completely new to R, the first few weeks will be a slog
- It will get better, I promise
\vfill
- Much of the material covered today comes from two (free!) sources:
- [\textcolor{kdisgreen}{R for Data Science}](https://r4ds.hadley.nz/)
- [\textcolor{kdisgreen}{R Markdown: The Definitive Guide}](https://bookdown.org/yihui/rmarkdown/)
\vfill
## What are R and RStudio?
\vfill
- R is a commonly used statistical program (and language)
- It is free and open source, which means you can use this after graduation, without paying for it
- R is CaSe SeNsItIvE
\vfill
- To work with R, we want to use an accompaniment called RStudio
- RStudio is what is referred to as an integrated development environment (IDE)
- It is not the only option (I use VS Code, for example), but it is the most common
- It makes working with R much easier
\vfill
- Whenever you start R, you want to start RStudio
- RStudio will start R for you
\vfill
## Some important considerations
\vfill
- One of our goals is to make **reproducible** research
- This means that we want to be able to share our code and have others be able to replicate our results
- To do this, we will use "scripts" that contain our code
\vfill
- A script should be self contained
- This means that it should contain all of the code necessary to run the analysis
- A well-written script should allow me to do everything without any additional information
\vfill
- We will also use R Markdown to create documents
- R Markdown is a way to combine text and code
- This allows us to create documents that are reproducible
- We will use R Markdown to create our homework assignments
- More on this in a bit
\vfill
## The RStudio interface
```{r rstudio1, echo = FALSE, message = FALSE, warning = FALSE, out.width = "90%", fig.align = "center"}
knitr::include_graphics(
path = "assets/rstudio1.png",
auto_pdf = TRUE
)
```
## The RStudio interface
```{r rstudio2, echo = FALSE, message = FALSE, warning = FALSE, out.width = "90%", fig.align = "center"}
knitr::include_graphics(
path = "assets/rstudio2.png",
auto_pdf = TRUE
)
```
## The RStudio interface
```{r rstudio3, echo = FALSE, message = FALSE, warning = FALSE, out.width = "90%", fig.align = "center"}
knitr::include_graphics(
path = "assets/rstudio3.png",
auto_pdf = TRUE
)
```
## The RStudio interface
```{r rstudio4, echo = FALSE, message = FALSE, warning = FALSE, out.width = "90%", fig.align = "center"}
knitr::include_graphics(
path = "assets/rstudio4.png",
auto_pdf = TRUE
)
```
## But we're missing something... what is it?
\pause
```{r rstudio5, echo = FALSE, message = FALSE, warning = FALSE, out.width = "90%", fig.align = "center"}
knitr::include_graphics(
path = "assets/rstudio5.png",
auto_pdf = TRUE
)
```
## The script
```{r rstudio6, echo = FALSE, message = FALSE, warning = FALSE, out.width = "90%", fig.align = "center"}
knitr::include_graphics(
path = "assets/rstudio6.png",
auto_pdf = TRUE
)
```
## Some notes
\vfill
- You can add comments to your script using a hashtag (#)
- At the top of ALL my scripts, I have a comment that says what the script does.
- At the top of your script, write a comment. It should say "# Week 1 - Introduction to R"
- I put LOTS of comments in my scripts. This is good practice.
\vfill
- You can run a line of code by clicking the "Run" button
- There are also shortcuts. On Mac it is command + enter. On windows it is control + enter. You can change these if you want.
\vfill
- You can run multiple lines of code by highlighting them and clicking the "Run" button (or the shortcut)
\vfill
- We will practice these later
\vfill
# R Basics
## Object types
- R has a few different types of objects
- The most common are vectors, matrices, and data frames
- A "tibble" is a type of data frame used by the tidyverse package (more below)
- We will use data frames almost exclusively since we are working with datasets, but vectors are common, too
- You can create a vector using the c() function:
- Note how we create a new object using the assignment operator, <-. You can also use =.
\vfill
```{r vector, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
vec <- c(1, 2, 3, 4)
vec
```
## Object types
- You can check what type of object something is by using the class() function
- For example, if I want to check what type of object vec is, I would write class(vec)
- Note that the output is "numeric"
- This is because vec is a vector of numbers
- If I want to check whether it is a vector, I can write is.vector(vec)
- Note that the output is TRUE
\vfill
```{r vector2, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
vec <- c(1, 2, 3, 4)
class(vec)
is.vector(vec)
```
## First things first: the working directory
- The working directory is the folder that R is currently working in
- This is where R will look for files
- This is where R will save files
- This is where R will create files
- You can always write out an entire file path, but this is tedious
- More importantly, it makes your code less reproducible since the path is specific to YOUR computer
- One nice thing about R is that the working directory will automatically be where you open the script from
- Let's try this. Save your script to a folder on your computer, then open the script from that folder.
## First things first: the working directory
The working directory should be where you opened the file from. Check it like this:
```{r wd, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
getwd()
```
## R packages
\vfill
- R is a language that is built on packages
- Packages are collections of functions that do specific things
- R comes with a set of "base" packages that are installed automatically
\vfill
- We are going to use one package consistently, called the "tidyverse"
- This consists of a set of packages that are designed to work together, with data cleaning in mind
\vfill
## R packages
\vfill
The one exception to always using a script? I install packages in the CONSOLE. You can install packages like this:
\vfill
```{r tidyinstall, echo = TRUE, eval = FALSE, message = FALSE, warning = FALSE, size = "tiny"}
install.packages("tidyverse")
```
\vfill
## Loading R packages in your script
\vfill
We need to load any R packages we want to use at the very top of the script. You should have a comment on line one, so on line two write:
\vfill
```{r tidyverse, echo = TRUE, eval = FALSE, message = FALSE, warning = FALSE, size = "tiny"}
library("tidyverse")
```
\vfill
This will load the tidyverse package.
\vfill
## Loading data
\vfill
- Go to the class website and download the data for today.
- Put it in your WORKING DIRECTORY (where the script is)
\vfill
- We will use the read_csv() function to load the data
- This function is part of the tidyverse package
- It will create a data frame
- We need to NAME the object (data frame). As before, note the assignment operator (<-). You can actually use = though.
\vfill
```{r data, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
library(tidyverse)
# read in the data
data <- read_csv("data.csv")
```
\vfill
## Objects in memory
The data frame should show up in the upper right hand corner of RStudio.
```{r rstudio7, echo = FALSE, message = FALSE, warning = FALSE, out.width = "90%", fig.align = "center"}
knitr::include_graphics(
path = "assets/rstudio7.png",
auto_pdf = TRUE
)
```
## Objects in memory
Click on the arrow and it will show more information.
```{r rstudio8, echo = FALSE, message = FALSE, warning = FALSE, out.width = "90%", fig.align = "center"}
knitr::include_graphics(
path = "assets/rstudio8.png",
auto_pdf = TRUE
)
```
## Objects in memory
\vfill
- The data frame is a matrix
- Each row is an observation and each column is a variables
\vfill
- We can also see the names of the columns like this:
\vfill
```{r colnames, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
colnames(data)
```
\vfill
- This is the kind of thing I might do in the console since it's not really required for the script.
\vfill
## Calling variables in R
- Some of you might be used to Stata
- One big difference between the two is that Stata generally only has one data frame in memory at a time
- This means that you can call a variable *without referencing the data frame*
- In R, if you want to look at a variable, you have to tell R which data frame it is in
- This is done with the $ operator
- For example, if I want to look at the variable "age" in the data frame "data", I would write data$age
- Let's look at summary statistics for age:
\vfill
```{r callingvar, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
summary(data$age)
```
## Summary statistics for the entire data frame
- You can also use summary on the data frame instead of a single column
- It helps to think of a data frame as rows and columns. For variables, you want to call specific columns.
- Look at the difference here (it cuts off because of the size of the slide):
\vfill
```{r sumstats, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
summary(data)
```
## Calling rows/columns of a data frame (matrix)
- Think about how we refer to rows and columns in a matrix.
- We use the row and column number, in that order.
- For example, if I want the first row and second column of a matrix $X$, mathematically I could write $X_{1,2}$
- We do *the same thing in R*
- If I want the first row and second column of the data frame "data", I would write data[1,2]
- Note that we use square brackets instead of parentheses
- Note that we use a comma to separate the row and column
\vfill
```{r rowcolumn, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
data[1,2]
```
## Calling columns of a data frame (matrix)
- We can call entire columns of a data frame by leaving the row blank
- For example, if I want the second column of the data frame "data", I would write data[,2]
- Note that the second column is the ability variable
\vfill
```{r column, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
colnames(data)
data[,2]
```
## Missing variables R
- Missing variables are denoted by NA
- This is different from Stata, which uses a period (.)
- Note that this is only how the PROGRAM stores missing variables. Sometimes the data itself has different missing values. \textcolor{red}{PAY ATTENTION!}
- For example, take a look at the first ten rows of the data frame (also note how I call the first ten rows and leave out the first column!):
\vfill
```{r missing, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
data[1:10,-1]
```
## Variable types
- R also has a few different types of variables
- The most common are numeric, character, and logical
- Look at the previous code again:
\vfill
```{r missing2, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
data[1:10,-1]
```
## Variable types
- dbl is short for double, which is a numeric variable (the "type" of numeric variable is about how much memory is needed to store it)
- chr is short for character, which is a string of characters (text)
- Surprisingly, in our previous example, educyears was a character string even though it seemed to be a number
- Let's look at the possible values of educyears using the unique() function, which outputs a vector:
\vfill
```{r uniqueeducyears, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
unique(data$educyears)
```
## Variable types
- Interesting! It seems that there is a "Not Mentioned" value.
- What if we want to replace those with missing, instead?
- Let's talk through the following code
- First note how it refers to a specific column and then a specific row
- Also note how it uses two equal signs (==) to check whether the value is "Not Mentioned"
- This is similar to Stata!
\vfill
```{r replace, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
# replace "Not Mentioned" with NA
data$educyears[data$educyears == "Not Mentioned"] <- NA
# check that it worked by looking at the unique values
unique(data$educyears)
# turn into numeric
data$educyears <- as.numeric(data$educyears)
class(data$educyears)
```
## Pipes
- One of the most useful things in R is the pipe operator (%>%)
- This is part of the tidyverse package
- It allows you to chain commands together
- It makes your code much easier to read
- It makes your code much easier to write
- It makes your code much easier to debug
- It makes your code much easier to share
- It makes your code much easier to reproduce
\vfill
- It's easy to use but it will take some time for you to get used to the names of the functions we can use with it
- This also goes for other tasks in R, not just with the pipe operator
## Pipes example
Here is an example of how we can use pipes with the mutate() function in tidyverse
- We are also going to use ifelse() to make this work
\vfill
```{r replacemutate, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
data <- data %>%
mutate(educyears = ifelse(educyears == "Not Mentioned", NA, educyears), # if educyears=="Not Mentioned", replace
educyears = as.numeric(educyears)) # replace educyears as numeric (instead of character)
summary(data$educyears)
```
\vfill\pause
Note that we could wrap as.numeric() around the ifelse() command to do it on one line!
\vfill
```{r replacemutate2, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
data <- data %>%
mutate(educyears = as.numeric(ifelse(educyears == "Not Mentioned", NA, educyears))) # wrapped into one line
summary(data$educyears)
```
## Missings and functions in R
In Stata, by default, functions ignore missing values
- R does not do this by default. Look at this:
\vfill
```{r missingsNA, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
data <- data %>%
mutate(educyears = as.numeric(ifelse(educyears == "Not Mentioned", NA, educyears))) # wrapped into one line
mean(data$educyears)
```
\vfill
If there are any missing values, the function will evalute to missing!
- But we can also do this:
\vfill
```{r missingsNA2, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
data <- data %>%
mutate(educyears = as.numeric(ifelse(educyears == "Not Mentioned", NA, educyears))) # wrapped into one line
mean(data$educyears, na.rm = TRUE) # BE CAREFUL WITH THIS! Make sure it is indeed what you want to do.
```
## Functions and storing values
The mean() function in the previous slide outputs a single value
- That means we could store that value as an object:
\vfill
```{r storingvalues, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
data <- data %>%
mutate(educyears = as.numeric(ifelse(educyears == "Not Mentioned", NA, educyears))) # wrapped into one line
meaneduc <- mean(data$educyears, na.rm = TRUE)
sdeduc <- sd(data$educyears, na.rm = TRUE)
meaneduc
sdeduc
```
\vfill
How is this helpful? We can use these values later in our script!
## Functions and mutate()
We can combine the mean() and sd() functions within mutate to create a new, standardized variable:
\vfill
```{r mutate_std, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
data <- data %>%
mutate(educyears = as.numeric(ifelse(educyears == "Not Mentioned", NA, educyears)), # wrapped into one line
educyears_std = (educyears - mean(educyears))/sd(educyears))
summary(data$educyears_std)
```
\vfill
Oh no! what happened?
## Functions and mutate()
We can combine the mean() and sd() functions within mutate to create a new, standardized variable:
\vfill
```{r mutate_std2, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
data <- data %>%
mutate(educyears = as.numeric(ifelse(educyears == "Not Mentioned", NA, educyears)), # wrapped into one line
educyears_std = (educyears - mean(educyears, na.rm = T))/sd(educyears, na.rm = T))
summary(data$educyears_std)
```
\vfill
Note that we can shorten TRUE to T (or FALSE to F).
## Visualizations with ggplot2
- ggplot2 is a flexible way to create visualizations in R
- The basic idea is that you create a plot object and then add layers to it
- Let's create a histogram of educyears
## Visualizations with ggplot2
```{r ggplot, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny", out.width = "45%", fig.align = "center"}
data <- data %>%
mutate(educyears = as.numeric(ifelse(educyears == "Not Mentioned", NA, educyears)))
# we call ggplot() and NOT ggplot2()
ggplot() + # note how we use + here, NOT the pipe operator
geom_histogram(data = data, aes(x = educyears)) # the histogram with geom_histogram
# data = data tells R to use the data frame "data", and the aes() is the aesthetic
# only an x value here since a histogram uses just a SINGLE value
```
## Visualizations with ggplot2
```{r ggplot2, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny", out.width = "45%", fig.align = "center"}
data <- data %>%
mutate(educyears = as.numeric(ifelse(educyears == "Not Mentioned", NA, educyears)))
# we can save the plot as an object
g1 <- ggplot() +
geom_histogram(data = data, aes(x = educyears))
g1
```
## Visualizations with ggplot2
```{r ggplot3, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny", out.width = "45%", fig.align = "center"}
data <- data %>%
mutate(educyears = as.numeric(ifelse(educyears == "Not Mentioned", NA, educyears)))
# lots of ways to change the plot
g1 <- ggplot() +
geom_histogram(data = data, aes(x = educyears)) +
labs(title = "Histogram of educyears",
x = "Years of education",
y = "Count")
g1
```
## One more example
```{r ggplot4, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny", out.width = "45%", fig.align = "center"}
data <- data %>%
mutate(educyears = as.numeric(ifelse(educyears == "Not Mentioned", NA, educyears)))
g1 <- ggplot() +
geom_histogram(data = data, aes(x = educyears)) +
labs(title = "Histogram of educyears",
x = "Years of education",
y = "Count") +
theme_minimal()
g1
```
## Let's try this with a NEW dataset
First install a new package that has a dataset we will use (you can do this in the console):
```{r install, echo = TRUE, eval = FALSE, message = FALSE, warning = FALSE, size = "tiny", out.width = "45%", fig.align = "center"}
install.packages("nycflights13")
```
\vfill
Now let's see:
```{r flights, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny", out.width = "45%", fig.align = "center"}
library(nycflights13)
glimpse(flights)
```
## Let's look at some new tidyverse functions
\vfill
Let's get the average departure delay by NYC airport:
\vfill
```{r flights2, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
flights %>%
group_by(origin) %>% # this groups ROWS based on their origin value
summarize(avg_dep_delay = mean(dep_delay, na.rm = T)) # this summarizes the data, creating means absed on the grouping!
```
\vfill
Note that this does not create a single value. Instead it creates a tibble (a data frame) summarizing the data by our grouping variable.
\vfill
## Let's look at some new tidyverse functions
\vfill
What if we want to save that tibble instead?
\vfill
```{r flights3, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny"}
summat <- flights %>%
group_by(origin) %>% # this groups ROWS based on their origin value
summarize(avg_dep_delay = mean(dep_delay, na.rm = T)) # this summarizes the data, creating means based on groups!
summat # print the 3x2 matrix in the console
```
\vfill
I could then output this to a table if I wanted to (using Markdown, more on this later):
```{r flights4, echo = FALSE, message = FALSE, warning = FALSE, size = "tiny"}
summat <- flights %>%
group_by(origin) %>% # this groups ROWS based on their origin value
summarize(avg_dep_delay = mean(dep_delay, na.rm = T)) # this summarizes the data, creating means based on groups!
kable(summat,
align = "c", linesep = "") %>%
kable_classic_2()
```
## Let's look at a new plot
How does departure delay vary by time of day?
\vfill
```{r flights5, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny", out.width = "55%", fig.align = "center"}
ggplot() +
geom_smooth(data = flights, aes(x = sched_dep_time, y = dep_delay))
```
## Let's look at a new plot
We can color code by origin, too!
\vfill
```{r flights6, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny", out.width = "55%", fig.align = "center"}
ggplot() +
geom_smooth(data = flights, aes(x = sched_dep_time, y = dep_delay, color = origin))
```
## Make it prettier
```{r flights7, echo = TRUE, message = FALSE, warning = FALSE, size = "tiny", out.width = "55%", fig.align = "center"}
ggplot() +
geom_smooth(data = flights, aes(x = sched_dep_time, y = dep_delay, color = origin), se = FALSE) +
labs(x = "Scheduled departure time",
y = "Departure delay (minutes)") +
theme_minimal() + guides(color = guide_legend(title = "Departure airport"))
```
# R Markdown
## What is R Markdown?
- R Markdown is a way to combine text and code
- This allows us to create documents that are reproducible
- We will use R Markdown to create our homework assignments
- These slides were all created in R Markdown
- My papers are written in R Markdown (well, some of them are, anyway)
- [\textcolor{kdisgreen}{\textbf{Here}}](https://joshmerfeld.github.io/assets/papers/pollution2023.pdf) is an example
- Yihui Xie, J. J. Allaire, and Garrett Grolemund have an awesome -- free! -- resource on R Markdown, [\textcolor{kdisgreen}{\textbf{R Markdown: The Definitive Guide}}](https://bookdown.org/yihui/rmarkdown/)
## Installing R Markdown
\vfill
You'll need to install R Markdown. You can do this in the console:
\vfill
```{r installrmarkdown, echo = TRUE, eval = FALSE, message = FALSE, warning = FALSE, size = "tiny"}
install.packages("rmarkdown")
```
\vfill
## Creating an R Markdown document in RStudio
```{r rm1, echo = FALSE, message = FALSE, warning = FALSE, out.width = "90%", fig.align = "center"}
knitr::include_graphics(
path = "assets/rm1.png",
auto_pdf = TRUE
)
```
## Creating an R Markdown document in RStudio
```{r rm2, echo = FALSE, message = FALSE, warning = FALSE, out.width = "90%", fig.align = "center"}
knitr::include_graphics(
path = "assets/rm2.png",
auto_pdf = TRUE
)
```
## Creating an R Markdown document in RStudio
```{r rm3, echo = FALSE, message = FALSE, warning = FALSE, out.width = "90%", fig.align = "center"}
knitr::include_graphics(
path = "assets/rm3.png",
auto_pdf = TRUE
)
```
## Go ahead and save this document
- Go ahead and save this document in your working directory.
- One think about Markdown files is that it will ALWAYS set the working directory to where the file is saved whenever you "knit" the document.
- What is "knitting"?
- Knitting is the process of turning your R Markdown document into a pdf, html, or word document.
- We will just focus on pdfs for now.
## Knit it!
```{r rm4, echo = FALSE, message = FALSE, warning = FALSE, out.width = "90%", fig.align = "center"}
knitr::include_graphics(
path = "assets/rm4.png",
auto_pdf = TRUE
)
```
## Check out the document you just created
- Go to your working directory and open the pdf to see what it looks like.
- It will always create the pdf in the same folder as the .Rmd file.
## YAML header
\vfill
- At the very top of the document is some information about the document
- This is called the YAML header
- It tells R Markdown what kind of document to create
- It also allows you to set some options
- DO NOT DELETE THE --- AT THE TOP AND BOTTOM OF THE YAML HEADER!
\vfill
- You can change the title and date as you please
- For today's date, you can use Sys.Date() within R inline code (more in a second):
\vfill
```{r date, echo = TRUE, eval = FALSE, message = FALSE, warning = FALSE, size = "tiny", out.width = "55%", fig.align = "center"}
date: "`r Sys.Date()`"
```
\vfill
## The setup chunk
- Just below the YAML header you'll see a "code chunk" called "setup" (r setup, include = FALSE)
- Note how it has $```$ and $```$ at the top and bottom. This differentiates the "code chunk" from the rest of the document.
- Whenever you want to add a code chunk, you *must* have the $```$ at the top and bottom of it, at the beginning of the line.
- Use the setup code chunk to load any packages or data that you want to use in the rest of the document.
- Later code chunks are "local": they will be able to access things from the setup chunk *but not from other code chunks*.