-
Notifications
You must be signed in to change notification settings - Fork 40
/
07-exploringdata2.Rmd
2233 lines (1677 loc) · 93.2 KB
/
07-exploringdata2.Rmd
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
# Exploring data #2
The video lectures for this chapter are embedded at relevant places in the text,
with links to download a pdf of the associated slides for each video.
You can also access [a full playlist for the videos for this chapter](https://www.youtube.com/playlist?list=PLuGPtwgRXxqIPno8Y8NMN1xpopJvK9RRQ).
```{r echo = FALSE, message = FALSE, warning = FALSE}
library(tidyverse)
library(knitr)
library(faraway)
data(worldcup)
library(ggthemes)
```
---
## Simple statistical tests in R
<iframe width="667" height="417" src="https://www.youtube.com/embed/JrM0bFff7Pw?list=PLuGPtwgRXxqIPno8Y8NMN1xpopJvK9RRQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
[Download](https://github.com/geanders/RProgrammingForResearch/raw/master/slides/CourseNotes_Week7_part_2.pdf)
a pdf of the lecture slides for this video.
<iframe width="667" height="417" src="https://www.youtube.com/embed/QyQTFumtLCE?list=PLuGPtwgRXxqIPno8Y8NMN1xpopJvK9RRQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
[Download](https://github.com/geanders/RProgrammingForResearch/raw/master/slides/CourseNotes_Week7_part_3.pdf)
a pdf of the lecture slides for this video.
Let's pull the fatal accident data just for the county that includes Las Vegas, NV.
Each US county has a unique identifier (FIPS code), composed of a two-digit state FIPS and a three-digit county FIPS code. The state FIPS for Nevada is 32; the county FIPS for Clark County is 003. Therefore, we can filter down to Clark County data in the FARS data we collected with the following code:
```{r message = FALSE, error = FALSE}
library(readr)
library(dplyr)
clark_co_accidents <- read_csv("data/accident.csv") %>%
filter(STATE == 32 & COUNTY == 3)
```
We can also check the number of accidents:
```{r}
clark_co_accidents %>%
count()
```
We want to test if the probability, on a Friday or Saturday, of a fatal accident occurring is higher than on other days of the week. Let's clean the data up a bit as a start:
```{r message = FALSE, warning = FALSE}
library(tidyr)
library(lubridate)
clark_co_accidents <- clark_co_accidents %>%
select(DAY, MONTH, YEAR) %>%
unite(date, DAY, MONTH, YEAR, sep = "-") %>%
mutate(date = dmy(date))
```
Here's what the data looks like now:
```{r}
clark_co_accidents %>%
slice(1:5)
```
Next, let's get the count of accidents by date:
```{r}
clark_co_accidents <- clark_co_accidents %>%
group_by(date) %>%
count() %>%
ungroup()
clark_co_accidents %>%
slice(1:3)
```
We're missing the dates without a fatal crash, so let's add those. First, create a dataframe
with all dates in 2016:
```{r}
all_dates <- tibble(date = seq(ymd("2016-01-01"),
ymd("2016-12-31"), by = 1))
all_dates %>%
slice(1:5)
```
Then merge this with the original dataset on Las Vegas fatal crashes and make any day missing from the fatal crashes dataset have a "0" for number of fatal accidents (`n`):
```{r}
clark_co_accidents <- clark_co_accidents %>%
right_join(all_dates, by = "date") %>%
# If `n` is missing, set to 0. Otherwise keep value.
mutate(n = ifelse(is.na(n), 0, n))
clark_co_accidents %>%
slice(1:3)
```
Next, let's add some information about day of week and weekend:
```{r}
clark_co_accidents <- clark_co_accidents %>%
mutate(weekday = wday(date, label = TRUE),
weekend = weekday %in% c("Fri", "Sat"))
clark_co_accidents %>%
slice(1:3)
```
Now let's calculate the probability that a day has at least one fatal crash, separately for weekends and weekdays:
```{r}
clark_co_accidents <- clark_co_accidents %>%
mutate(any_crash = n > 0)
crash_prob <- clark_co_accidents %>%
group_by(weekend) %>%
summarize(n_days = n(),
crash_days = sum(any_crash)) %>%
mutate(prob_crash_day = crash_days / n_days)
crash_prob
```
In R, you can use `prop.test` to test if two proportions are equal. Inputs include the total number of trials in each group (`n =`) and the number of "successes"" (`x = `):
```{r}
prop.test(x = crash_prob$crash_days,
n = crash_prob$n_days)
```
I won't be teaching in this course how to find the correct statistical test. That's
something you'll hopefully learn in a statistics course. There are also a variety of books that can help you with this, including some that you can access free online through CSU's library. One servicable introduction is "Statistical Analysis with R for Dummies".
You can create an object from the output of any statistical test in R. Typically, this will be (at least at some level) in an object class called a "list":
```{r}
vegas_test <- prop.test(x = crash_prob$crash_days,
n = crash_prob$n_days)
is.list(vegas_test)
```
So far, we've mostly worked with two object types in R, **dataframes** and **vectors**. In the next subsection we'll look more at two object classes we haven't looked at much,
**matrices** and **lists**. Both have important roles once you start applying more
advanced methods to analyze your data.
<iframe width="667" height="417" src="https://www.youtube.com/embed/YvTdwfgRHqU?list=PLuGPtwgRXxqIPno8Y8NMN1xpopJvK9RRQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
[Download](https://github.com/geanders/RProgrammingForResearch/raw/master/slides/CourseNotes_Week7_part_1.pdf)
a pdf of the lecture slides for this video.
## Matrices
A matrix is like a data frame, but all the values in all columns must be of the same class (e.g., numeric, character). R uses matrices a lot for its underlying math (e.g., for the linear algebra operations required for fitting regression models). R can do matrix operations quite quickly.
You can create a matrix with the `matrix` function. Input a vector with the values to fill the matrix and `ncol` to set the number of columns:
```{r cab}
foo <- matrix(1:10, ncol = 5)
foo
```
By default, the matrix will fill up by column. You can fill it by row with the `byrow` function:
```{r cac}
foo <- matrix(1:10, ncol = 5, byrow = TRUE)
foo
```
In certain situations, you might want to work with a matrix instead of a data frame (for example, in cases where you were concerned about speed -- a matrix is more memory efficient than the corresponding data frame). If you want to convert a data frame to a matrix, you can use the `as.matrix` function:
```{r cad}
foo <- tibble(col_1 = 1:2, col_2 = 3:4,
col_3 = 5:6, col_4 = 7:8,
col_5 = 9:10)
(foo <- as.matrix(foo))
```
You can index matrices with square brackets, just like data frames:
```{r cae}
foo[1, 1:2]
```
You cannot, however, use `dplyr` functions with matrices:
```{r caf, eval = FALSE}
foo %>% filter(col_1 == 1)
```
All elements in a matrix must have the same class.
The matrix will default to make all values the most general class of any of the values, in any column. For example, if we replaced one numeric value with the character "a", everything would turn into a character:
```{r cag}
foo[1, 1] <- "a"
foo
```
---
## Lists
A list has different elements, just like a data frame has different columns. However, the different elements of a list can have different lengths (unlike the columns of a data frame). The different elements can also have different classes.
```{r cah}
bar <- list(some_letters = letters[1:3],
some_numbers = 1:5,
some_logical_values = c(TRUE, FALSE))
bar
```
To index an element from a list, use double square brackets. You can use bracket indexing either with numbers (which element in the list?) or with names:
```{r cai}
bar[[1]]
bar[["some_numbers"]]
```
You can also index lists with the `$` operator:
```{r caii}
bar$some_logical_values
```
To access a specific value within a list element we can index the element e.g.:
```{r caiii}
bar[[1]][[2]]
```
Lists can be used to contain data with an unusual structure and / or lots of different components. For example, the information from fitting a regression is often stored as a list:
```{r caj}
my_mod <- glm(rnorm(10) ~ c(1:10))
is.list(my_mod)
```
The `names` function returns the name of each element in the list:
```{r cak}
head(names(my_mod), 3)
my_mod[["coefficients"]]
```
A list can even contain other lists. We can use the `str` function to see the structure of a list:
```{r cakk}
a_list <- list(list("a", "b"), list(1, 2))
str(a_list)
```
Sometimes you'll see unnecessary lists-of-lists, perhaps when importing data into R created. Or a list with multiple elements that you would like to combine. You can remove a level of hierarchy from a list using the `flatten` function from the `purrr` package:
```{r cakl, warning = FALSE}
library(purrr)
a_list
flatten(a_list)
```
Let's look at the list object from the statistical test we ran for Las Vegas:
```{r}
str(vegas_test)
```
Using `str` to print out the list's structure doesn't produce the easiest to digest output. We can use the `jsonedit` function from the `listviewer` package to create a widget in the `viewer` pane to more esily explore our list.
```{r, eval=FALSE}
library(listviewer)
jsonedit(vegas_test)
```
We can pull out an element using the `$` notation:
```{r}
vegas_test$p.value
```
Or using the `[[` notation:
```{r}
vegas_test[[4]]
```
You may have noticed, though, that this output is not a tidy dataframe.
Ack! That means we can't use all the tidyverse tricks we've learned so far in the course!
Fortunately, David Robinson noticed this problem and came up with a package called `broom` that can "tidy up" a lot of these kinds of objects.
The `broom` package has three main functions:
- `glance`: Return a one-row, tidy dataframe from a model or other R object
- `tidy`: Return a tidy dataframe from a model or other R object
- `augment`: "Augment" the dataframe you input to the statistical function
Here is the output for `tidy` for the `vegas_test` object (`augment`
won't work for this type of object, and `glance` gives the same thing as `tidy`):
```{r}
library(broom)
tidy(vegas_test)
```
---
## Apply a test multiple times
<iframe width="738" height="461" src="https://www.youtube.com/embed/RvPS6HZD3t8?list=PLuGPtwgRXxqIPno8Y8NMN1xpopJvK9RRQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
[Download](https://github.com/geanders/RProgrammingForResearch/raw/master/slides/CourseNotes_Week7_part_6.pdf)
a pdf of the lecture slides for this video.
<iframe width="646" height="404" src="https://www.youtube.com/embed/PWLzdd_n61o?list=PLuGPtwgRXxqIPno8Y8NMN1xpopJvK9RRQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
[Download](https://github.com/geanders/RProgrammingForResearch/raw/master/slides/CourseNotes_Week7_part_7.pdf)
a pdf of the lecture slides for this video.
<iframe width="646" height="404" src="https://www.youtube.com/embed/djNbWXhhDRs?list=PLuGPtwgRXxqIPno8Y8NMN1xpopJvK9RRQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
[Download](https://github.com/geanders/RProgrammingForResearch/raw/master/slides/CourseNotes_Week7_part_8.pdf)
a pdf of the lecture slides for this video.
Often, we don't want to just apply a statistical test to our entire data set.
Let's look at an example from the `microbiome package`.
```{r, warning = FALSE, message = FALSE}
library(microbiome)
data(peerj32)
print(names(peerj32))
```
Like we saw before, the list-like `phyloseq` objects require a little tidying before we can use them easiliy.
```{r}
library(dplyr)
peerj32_tibble <- (psmelt(peerj32$phyloseq)) %>%
dplyr::select(-Sample) %>%
rename_all(tolower) %>%
as_tibble()
```
```{r, echo=FALSE}
slice(peerj32_tibble, 1:3)
```
We can make a plot from the resulting tibble to help us explore the data.
```{r, fig.height=8, fig.width=10}
library(ggplot2)
ggplot(peerj32_tibble, aes(x = subject, y = abundance, color = sex)) +
geom_point() +
theme_bw() +
facet_wrap(~phylum, ncol = 4, scales = "free") +
theme(axis.text.x = element_blank(),
legend.position = "top") +
xlab("Subject ID")
```
We can group the data by `phylum` and `group` and then use the `nest` function from the `tidyr` package to create a new dataframe containing the nested data:
```{r}
library(tidyr)
nested_data <- peerj32_tibble %>%
group_by(phylum, group) %>%
nest()
```
```{r}
slice(nested_data, 1:3)
```
We can then use the `map` function from the `purrr` package to apply functions to each nested dataframe. Let's start by counting the rows in each nested dataframe and filtering out dataframes with less than 25 rows.
```{r}
library(purrr)
filtered_data <- nested_data %>%
mutate(n_rows = purrr::map(data, ~ nrow(.x))) %>%
filter(n_rows > 25)
```
Now let's perform a t-test on each out the nested dataframes. Remember, each nested dataframe is one unique combination of phylum and group.
```{r}
t_tests <- filtered_data %>%
mutate(t_test = purrr::map(data, ~t.test(abundance ~ sex, data = .x)))
```
```{r}
t_tests
```
The resulting dataframe contains a new column, which contains the model objects. Just as we mapped the `t.test` function, we can map the *tidying* functions from the `broom` package to extract the information we want from the nested model objects.
```{r}
summary <- t_tests %>%
mutate(summary = purrr::map(t_test, broom::glance))
```
```{r}
summary
```
The final step is to return a tidy dataframe, we can do this using the `unnest` function from the `tidyr` package. Note: it is also wise to `ungroup` after you are done operating on your grouped variables - you may run into problems if you forget your dataframe is grouped later on!
```{r}
unnested <- summary %>%
unnest(summary) %>%
ungroup() %>%
dplyr::select(group, phylum, p.value)
```
```{r}
unnested
```
We can then plot the results. Let's do this for the "LGG" (non-placebo) group, using our principles for good graphics.
```{r}
p_data <- unnested %>%
filter(group == "LGG") %>%
mutate(phylum = fct_reorder(phylum, p.value))
ggplot(p_data, aes(y = p.value, x = phylum)) +
facet_wrap(~group) +
geom_bar(stat="identity", fill = "grey90", color = "grey20") +
coord_flip() +
theme_bw() +
ggtitle("Difference in abundance by gender") +
xlab("") + ylab("p-value from t-test")
```
## Regression models
<iframe width="667" height="417" src="https://www.youtube.com/embed/qGL6kdJIVU0?list=PLuGPtwgRXxqIPno8Y8NMN1xpopJvK9RRQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
[Download](https://github.com/geanders/RProgrammingForResearch/raw/master/slides/CourseNotes_Week7_part_4.pdf)
a pdf of the lecture slides for this video.
<iframe width="667" height="417" src="https://www.youtube.com/embed/XW8QB8nlSIc?list=PLuGPtwgRXxqIPno8Y8NMN1xpopJvK9RRQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
[Download](https://github.com/geanders/RProgrammingForResearch/raw/master/slides/CourseNotes_Week7_part_5.pdf)
a pdf of the lecture slides for this video.
### Formula structure
*Regression models* can be used to estimate how the expected value of a *dependent variable* changes as *independent variables* change. \medskip
In R, regression formulas take this structure:
```{r eval = FALSE}
## Generic code
[response variable] ~ [indep. var. 1] + [indep. var. 2] + ...
```
Notice that a tilde, `~`, is used to separate the independent and dependent variables and that a plus sign, `+`, is used to join independent variables. This format mimics the statistical notation:
$$
Y_i \sim X_1 + X_2 + X_3
$$
You will use this type of structure in R fo a lot of different function calls, including those for linear models (fit with the `lm` function) and generalized linear models (fit with the `glm` function).
There are some conventions that can be used in R formulas. Common ones include:
```{r echo = FALSE}
for_convs <- tibble(Convention = c("`I()`", "`:`", "`*`", "`.`",
"`1`", "`-`"),
Meaning = c("evaluate the formula inside `I()` before fitting (e.g., `I(x1 + x2)`)",
"fit the interaction between `x1` and `x2` variables",
"fit the main effects and interaction for both variables (e.g., `x1*x2` equals `x1 + x2 + x1:x2`)",
"include as independent variables all variables other than the response (e.g., `y ~ .`)",
"intercept (e.g., `y ~ 1` for an intercept-only model)",
"do not include a variable in the data frame as an independent variables (e.g., `y ~ . - x1`); usually used in conjunction with `.` or `1`"))
pander::pander(for_convs, split.cells = c(1,1,58),
justify = c("center", "left"))
```
### Linear models
To fit a linear model, you can use the function `lm()`. This function is part of the `stats` package, which comes installed with base R. In this function, you can use the `data` option to specify the data frame from which to get the vectors.
```{r, echo=FALSE}
library(forcats)
nepali_fct <- as_tibble(nepali) %>%
mutate(sex = fct_recode(factor(sex), Male = "1", Female = "2"))
```
```{r}
mod_a <- lm(wt ~ ht, data = nepali)
```
This previous call fits the model:
$$ Y_{i} = \beta_{0} + \beta_{1}X_{1,i} + \epsilon_{i} $$
where:
- $Y_{i}$ : weight of child $i$
- $X_{1,i}$ : height of child $i$
If you run the `lm` function without saving it as an object, R will fit the regression and print out the function call and the estimated model coefficients:
```{r}
lm(wt ~ ht, data = nepali)
```
However, to be able to use the model later for things like predictions and model assessments, you should save the output of the function as an R object:
```{r}
mod_a <- lm(wt ~ ht, data = nepali)
```
This object has a special class, `lm`:
```{r}
class(mod_a)
```
This class is a special type of list object. If you use `is.list` to check, you can confirm that this object is a list:
```{r}
is.list(mod_a)
```
There are a number of functions that you can apply to an `lm` object. These include:
```{r echo = FALSE}
mod_objects <- tibble(Function = c("`summary`", "`coefficients`",
"`fitted`",
"`plot`", "`residuals`"),
Description = c("Get a variety of information on the model, including coefficients and p-values for the coefficients",
"Pull out just the coefficients for a model",
"Get the fitted values from the model (for the data used to fit the model)",
"Create plots to help assess model assumptions",
"Get the model residuals"))
pander::pander(mod_objects, split.cells = c(1,1,58),
justify = c("center", "left"))
```
For example, you can get the coefficients from the model by running:
```{r}
coefficients(mod_a)
```
The estimated coefficient for the intercept is always given under the name "(Intercept)". Estimated coefficients for independent variables are given based on their column names in the original data ("ht" here, for $\beta_1$, or the estimated increase in expected weight for a one unit increase in height).
You can use the output from a `coefficients` call to plot a regression line based on the model fit on top of points showing the original data (Figure \@ref(fig:modelcoefplot)).
```{r modelcoefplot, fig.height = 3.5, fig.width = 5, warning = FALSE, fig.align = "center", fig.cap = "Example of using the output from a coefficients call to add a regression line to a scatterplot."}
mod_coef <- coefficients(mod_a)
ggplot(nepali, aes(x = ht, y = wt)) +
geom_point(size = 0.2) +
xlab("Height (cm)") + ylab("Weight (kg)") +
geom_abline(aes(intercept = mod_coef[1],
slope = mod_coef[2]), col = "blue")
```
```{block, type = "rmdnote"}
You can also add a linear regression line to a scatterplot by adding the geom `geom_smooth` using the argument `method = "lm"`.
```
You can use the function `residuals` on an `lm` object to pull out the residuals from the model fit:
```{r}
head(residuals(mod_a))
```
The result of a `residuals` call is a vector with one element for each of the non-missing observations (rows) in the data frame you used to fit the model. Each value gives the different between the model fitted value and the observed value for each of these observations, in the same order the observations show up in the data frame. The residuals are in the same order as the observations in the original data frame.
```{block, type = "rmdtip"}
You can also use the shorter function `coef` as an alternative to `coefficients` and the shorter function `resid` as an alternative to `residuals`.
```
As noted in the subsection on simple statistics functions, the `summary` function returns different output depending on the type of object that is input to the function. If you input a regression model object to `summary`, the function gives you a lot of information about the model. For example, here is the output returned by running `summary` for the linear regression model object we just created:
```{r}
summary(mod_a)
```
This output includes a lot of useful elements, including (1) basic summary statistics for the residuals (to meet model assumptions, the median should be around zero and the absolute values fairly similar for the first and third quantiles), (2) coefficient estimates, standard errors, and p-values, and (3) some model summary statistics, including residual standard error, degrees of freedom, number of missing observations, and F-statistic.
The object returned by the `summary()` function when it is applied to an `lm` object is a list, which you can confirm using the `is.list` function:
```{r}
is.list(summary(mod_a))
```
With any list, you can use the `names` function to get the names of all of the different elements of the object:
```{r}
names(summary(mod_a))
```
You can use the `$` operator to pull out any element of the list. For example, to pull out the table with information on the estimated model coefficients, you can run:
```{r}
summary(mod_a)$coefficients
```
The `plot` function, like the `summary` function, will give different output depending on the class of the object that you input. For an `lm` object, you can use the `plot` function to get a number of useful diagnostic plots that will help you check regression assumptions (Figure \@ref(fig:plotlmexample)):
```{r eval = FALSE}
plot(mod_a)
```
```{r plotlmexample, echo = FALSE, out.width = '\\textwidth', fig.align = "center", fig.cap = "Example output from running the plot function with an lm object as the input."}
oldpar <- par(mfrow = c(2, 2))
plot(mod_a)
par(oldpar)
```
You can also use binary variables or factors as independent variables in regression models. For example, in the `nepali` dataset, `sex` is a factor variable with the levels "Male" and "Female". You can fit a linear model of weight regressed on sex for this data with the call:
```{r}
mod_b <- lm(wt ~ sex, data = nepali)
```
This call fits the model:
$$ Y_{i} = \beta_{0} + \beta_{1}X_{1,i} + \epsilon_{i} $$
where $X_{1,i}$ : sex of child $i$, where 0 = male and 1 = female.
Here are the estimated coefficients from fitting this model:
```{r}
summary(mod_b)$coefficients
```
You'll notice that, in addition to an estimated intercept (`(Intercept)`), the other estimated coefficient is `sexFemale` rather than just `sex`, although the column name in the data frame input to `lm` for this variable is `sex`.
This is because, when a factor or binary variable is input as an independent variable in a linear regression model, R will fit an estimated coefficient for all levels of factors *except* the first factor level. By default, this first factor level is used as the baseline level, and so its estimated mean is given by the estimated intercept, while the other model coefficients give the estimated *difference* from this baseline.
For example, the model fit above tells us that the estimated mean weight of males is `r round(coef(mod_b)[1], 1)`, while the estimated mean weight of females is `r round(coef(mod_b)[1], 1)` + `r round(coef(mod_b)[2], 1)` = `r round(coef(mod_b)[1], 1) + round(coef(mod_b)[2], 1)`.
<!-- If you would prefer that a different level of the factor be the baseline (for example, "Female" rather than "Male" for the previous regression), you can do that by using the `levels` argument in the `factor` function to reset factor levels. For example: -->
<!-- ```{r} -->
<!-- nepali_reset <- nepali %>% -->
<!-- mutate(sex = factor(sex, levels = c("2", "1"))) -->
<!-- mod_b_reset <- lm(wt ~ sex, data = nepali_reset) -->
<!-- summary(mod_b_reset)$coef -->
<!-- ``` -->
<!-- Now, `(Intercept)` gives the estimated mean weight for females, while the second estimated coefficient gives the estimated mean difference for males compared to the expected value for females. -->
---
## Handling model objects
The `broom` package contains tools for converting statistical objects into nice tidy data frames. The tools in the `broom` package make it easy to process statistical results in R using the tools of the `tidyverse`.
### broom::tidy
The `tidy()` function returns a data frame with information on the fitted model terms. For example, when applied to one of our linear models we get:
```{r tidy_example}
library(broom)
kable(tidy(mod_a), digits = 3)
```
```{r tidy_class}
class(tidy(mod_a))
```
You can pass arguments to the `tidy()` function. For example, include confidence intervals:
```{r tidy_cis}
kable(tidy(mod_a, conf.int = TRUE), digits = 3)
```
---
### broom::augment
The `augment()` function adds information about a fitted model to the dataset used to fit the model. For example, when applied to one of our linear models we get information on the fitted values and residuals included in the output:
```{r augment_example, warning = FALSE}
kable(head(broom::augment(mod_a), 3), digits = 3)
```
---
### broom::glance
The `glance()` functions returns a one row summary of a fitted model object: For example:
```{r glance_example, warning = FALSE}
kable(glance(mod_a, conf.int = TRUE), digits = 3)
```
---
### References-- statistics in R
One great (and free online for CSU students through our library) book to find out more about using R for basic statistics is:
- [Introductory Statistics with R](http://discovery.library.colostate.edu/Record/.b44705323)
If you want all the details about fitting linear models and GLMs in R, Julian Faraway's books are fantastic. He has one on linear models and one on extensions including logistic and Poisson models:
- [Linear Models with R](http://discovery.library.colostate.edu/Record/.b41119691) (also free online through the CSU library)
- [Extending the Linear Model with R](http://www.amazon.com/Extending-Linear-Model-Generalized-Nonparametric/dp/158488424X/ref=sr_1_1?ie=UTF8&qid=1442252668&sr=8-1&keywords=extending+linear+model+r)
---
## Functions
<iframe width="646" height="404" src="https://www.youtube.com/embed/4QAKphImJd8?list=PLuGPtwgRXxqIPno8Y8NMN1xpopJvK9RRQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
[Download](https://github.com/geanders/RProgrammingForResearch/raw/master/slides/CourseNotes_Week7_part_9.pdf)
a pdf of the lecture slides for this video.
<iframe width="646" height="404" src="https://www.youtube.com/embed/LRdh_FMaIUc?list=PLuGPtwgRXxqIPno8Y8NMN1xpopJvK9RRQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
[Download](https://github.com/geanders/RProgrammingForResearch/raw/master/slides/CourseNotes_Week7_part_10.pdf)
a pdf of the lecture slides for this video.
<iframe width="646" height="404" src="https://www.youtube.com/embed/ph3-4ILsL3Q?list=PLuGPtwgRXxqIPno8Y8NMN1xpopJvK9RRQ" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
[Download](https://github.com/geanders/RProgrammingForResearch/raw/master/slides/CourseNotes_Week7_part_11.pdf)
a pdf of the lecture slides for this video.
As you move to larger projects, you will find yourself using the same code a lot. \bigskip
Examples include:
- Reading in data from a specific type of equipment (air pollution monitor, accelerometer)
- Running a specific type of analysis
- Creating a specific type of plot or map
\bigskip
If you find yourself cutting and pasting a lot, convert the code to a function.
Advantages of writing functions include:
- Coding is more efficient
- Easier to change your code (if you've cut and paste code and you want to change something, you have to change it everywhere - this is an easy way to accidentally create bugs in your code)
- Easier to share code with others
You can name a function anything you want (although try to avoid names of preexisting-existing functions). You then define any inputs (arguments; separate multiple arguments with commas) and put the code to run in braces:
```{r, eval = FALSE}
## Note: this code will not run
[function name] <- function([any arguments]){
[code to run]
}
```
Here is an example of a very basic function. This function takes a number as input and adds 1 to that number.
```{r}
add_one <- function(number){
out <- number + 1
return(out)
}
add_one(number = 3)
add_one(number = -1)
```
- Functions can input any type of R object (for example, vectors, data frames, even other functions and ggplot objects)
- Similarly, functions can output any type of R object
- When defining a function, you can set default values for some of the parameters
- You can explicitly specify the value to return from the function
For example, the following function inputs a data frame (`datafr`) and a one-element vector (`child_id`) and returns only rows in the data frame where it's `id` column matches `child_id`. It includes a default value for `datafr`, but not for `child_id`.
```{r}
subset_nepali <- function(datafr = nepali, child_id){
datafr <- datafr %>%
filter(id == child_id)
return(datafr)
}
```
If an argument is not given for a parameter with a default, the function will run using the default value for that parameter. For example:
```{r}
subset_nepali(child_id = "120011")
```
If an argument is not given for a parameter without a default, the function call will result in an error. For example:
```{r error = TRUE}
subset_nepali(datafr = nepali)
```
By default, the function will return the last defined object, although the choice of using `return` can affect printing behavior when you run the function. For example, I could have written the `subset_nepali` function like this:
```{r}
subset_nepali <- function(datafr = nepali, child_id){
datafr <- datafr %>%
filter(id == child_id)
}
```
In this case, the output will not automatically print out when you call the function without assigning it to an R object:
```{r}
subset_nepali(child_id = "120011")
```
However, the output can be assigned to an R object in the same way as when the function was defined without `return`:
```{r}
first_childs_data <- subset_nepali(child_id = "120011")
first_childs_data
```
```{block, type = 'rmdwarning'}
R is very "good" at running functions! It will look for (scope) the variables in your function in various places (environments). So your functions may run even when you don't expect them to, potentially, with unexpected results!
```
The `return` function can also be used to return an object other than the last defined object (although this doesn't tend to be something you need to do very often). If you did not use `return` in the following code, it will output "Test output":
```{r}
subset_nepali <- function(datafr = nepali, child_id){
datafr <- datafr %>%
filter(id == child_id)
a <- "Test output"
}
(subset_nepali(child_id = "120011"))
```
Conversely, you can use `return` to output `datafr`, even though it's not the last object defined:
```{r}
subset_nepali <- function(datafr = nepali, child_id){
datafr <- datafr %>%
filter(id == child_id)
a <- "Test output"
return(datafr)
}
subset_nepali(child_id = "120011")
```
---
### if / else statements
There are other control structures you can use in your R code. Two that you will commonly use within R functions are `if` and `ifelse` statements. \bigskip
An `if` statement tells R that, **if** a certain condition is true, **do** run some code. For example, if you wanted to print out only odd numbers between 1 and 5, one way to do that is with an `if` statement: (Note: the `%%` operator in R returns the remainder of the first value (i) divided by the second value (2).)
```{r}
for(i in 1:5){
if(i %% 2 == 1){
print(i)
}
}
```
The `if` statement runs some code if a condition is true, but does nothing if it is false. If you'd like different code to run depending on whether the condition is true or false, you can us an if / else or an if / else if / else statement.
```{r}
for(i in 1:5){
if(i %% 2 == 1){
print(i)
} else {
print(paste(i, "is even"))
}
}
```
What would this code do? \bigskip
```{r eval = FALSE}
for(i in 1:100){
if(i %% 3 == 0 & i %% 5 == 0){
print("FizzBuzz")
} else if(i %% 3 == 0){
print("Fizz")
} else if(i %% 5 == 0){
print("Buzz")
} else {
print(i)
}
}
```
If / else statements are extremely useful in functions. \bigskip
In R, the `if` statement evaluates everything in the parentheses and, if that evaluates to `TRUE`, runs everything in the braces. This means that you can trigger code in an `if` statement with a single-value logical vector:
```{r}
weekend <- TRUE
if(weekend){
print("It's the weekend!")
}
```
This functionality can be useful with parameters you choose to include when writing your own functions (e.g., `print = TRUE`).
### Some other control structures
The control structure you are most likely to use in data analysis with R is the "if / else" statement. However, there are a few other control structures you may occasionally find useful:
- `next`
- `break`
- `while`
You can use the `next` structure to skip to the next round of a loop when a certain condition is met. For example, we could have used this code to print out odd numbers between 1 and 5:
```{r}
i <- 0
while(i < 5){
i <- 1 + i
if(i %% 2 == 0){
next
}
print(i)
}
```
You can use `break` to break out of a loop if a certain condition is met. For example, the final code will break out of the loop once `i` is over 2, so it will only print the numbers 1 through 3:
```{r}
i <- 0
while(i <= 5){
if(i > 2){
break
}
i <- 1 + i
print(i)
}
```
## In-course exercise for Chapter 7
### Exploring taxonomic profiling data
- We'll be using a package on Bioconductor called `microbiome`. You'll need to install that package from Bioconductor. This uses code that's different from the default you use to download a package from CRAN. Go to [the Bioconductor page for the microbiome package](https://bioconductor.org/packages/release/bioc/html/microbiome.html) and figure out how to install this package based on instructions on that page.
- The `microbiome` that includes tools for exploring and analysing microbiome profiling data. This package has a website with tutorial information [here](https://bioconductor.org/packages/devel/bioc/vignettes/microbiome/inst/doc/vignette.html#installation). We want to explore a dataset on genus-level microbiota profiling (`atlas1006`). Navigate to the tutorial webpage to figure out how you can get this example raw data loaded in your R session. Use the `class` and `str` functions to start exploring this data. Is it in a dataframe (tibble)? Is it in a tidy format? How is the data structured?
- On the [microbiome page](https://bioconductor.org/packages/devel/bioc/vignettes/microbiome/inst/doc/vignette.html), find the documentation describing the `atlas1006` data. Look through this documentation to figure out what information is included in the data. Also, check the helpfile for this dataset and look up the original article describing the data (you can find the article information in the help resources).
- The `atlas1006` data is stored in a special object class called a "phyloseq" object (you should have seen this when you used `class` with the object). You can pull certain parts of this data using special functions called "accessors". One is `get_variable`. Try running `get_variable` with the `atlas1006` data. What do you think this data is showing?
- Which different nationalities are represented by the study subjects, based on the dataframe you extracted in the last step? How many samples have each nationality? Which different BMI groups are included? Does it look like the study was balanced among these groups?
- Based on the data you extracted, does it look like diversity varies much between males and females? Across BMI groups?
- Discuss what steps you would need to take to create the following plot. To start, don't write any code, just develop a plan. Talk about what the dataset should look like right before you create the plot and what functions you could use to get the data from its current format to that format.
- Try to write the code to create this plot. This will include some code for cleaning the data and some code for plotting. I will add one example answer after class, but I'd like you to try to figure it out yourselves first.
```{r echo = FALSE, warning = FALSE, message = FALSE, fig.width = 8, fig.height = 4}
library(tidyverse)
library(ggthemes)
library(microbiome)
data(atlas1006)
atlas1006 %>%
get_variable() %>%
ggplot(aes(x = bmi_group, y = diversity, color = sex)) +
geom_boxplot(alpha = 0.2) +
facet_wrap(~ nationality)
```
#### Example R code
Install the `microbiome` package from Bioconductor:
```{r eval = FALSE}
if (!requireNamespace("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install("microbiome")
```
Load the `atlas1006` example data in the `microbiome` package and explore it with `str` and `class`:
```{r}
library(microbiome)
data(atlas1006)
class(atlas1006)
str(atlas1006)
```
Pull out the data frame that contains information on each study subject in the `atlas1006` data by using the `get_variable` accessor function:
```{r}
get_variable(atlas1006) %>% head()
```
**Note:** Since the first argument to `get_variable` is the phyloseq object (here, the `atlas1006` data object), you can pipe into the function, like this:
```{r eval = FALSE}
atlas1006 %>%
get_variable() %>%
head()
```
Find out the different nationalities included in the data:
```{r}