-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLearnR.html
More file actions
1078 lines (984 loc) · 39.9 KB
/
Copy pathLearnR.html
File metadata and controls
1078 lines (984 loc) · 39.9 KB
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>Getting started</title>
<script src="site_libs/header-attrs-2.11/header-attrs.js"></script>
<script src="site_libs/jquery-3.6.0/jquery-3.6.0.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<style>h1 {font-size: 34px;}
h1.title {font-size: 38px;}
h2 {font-size: 30px;}
h3 {font-size: 24px;}
h4 {font-size: 18px;}
h5 {font-size: 16px;}
h6 {font-size: 12px;}
code {color: inherit; background-color: rgba(0, 0, 0, 0.04);}
pre:not([class]) { background-color: white }</style>
<script src="site_libs/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-9.12.0/default.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<link href="site_libs/font-awesome-5.1.0/css/all.css" rel="stylesheet" />
<link href="site_libs/font-awesome-5.1.0/css/v4-shims.css" rel="stylesheet" />
<style type="text/css">
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<style type="text/css">code{white-space: pre;}</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
pre code {
padding: 0;
}
</style>
<style type="text/css">
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #adb5bd;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script type="text/javascript">
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark it active
menuAnchor.tab('show');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.dropdown').addClass('active');
// Navbar adjustments
var navHeight = $(".navbar").first().height() + 15;
var style = document.createElement('style');
var pt = "padding-top: " + navHeight + "px; ";
var mt = "margin-top: -" + navHeight + "px; ";
var css = "";
// offset scroll position for anchor links (for fixed navbar)
for (var i = 1; i <= 6; i++) {
css += ".section h" + i + "{ " + pt + mt + "}\n";
}
style.innerHTML = "body {" + pt + "padding-bottom: 40px; }\n" + css;
document.head.appendChild(style);
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "";
border: none;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs > li.active {
display: block;
}
.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
background-color: transparent;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
@media print {
.toc-content {
/* see https://github.com/w3c/csswg-drafts/issues/4434 */
float: right;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.90em;
}
.tocify .list-group-item {
border-radius: 0px;
}
</style>
</head>
<body>
<div class="container-fluid main-container">
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-9">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">Beginner guide to R</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="index.html">Home</a>
</li>
<li>
<a href="LearnR.html">Getting started</a>
</li>
<li>
<a href="LearnR2.html">Advanced options</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="https://github.com/SaraBaart">
<span class="fab fa-github fa-lg"></span>
</a>
</li>
<li>
<a href="https://twitter.com/SaraBaart">
<span class="fab fa-twitter fa-lg"></span>
</a>
</li>
<li>
<a href="https://www.linkedin.com/in/sara-baart-8109a422/">
<span class="fab fa-linkedin fa-lg"></span>
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div id="header">
<h1 class="title toc-ignore">Getting started</h1>
</div>
<p>Once you have installed R and Rstudio, we can get started with R! </p>
<p><strong>IMPORTANT</strong> : R is case sensitive. This means that <code>mean(variable)</code> is not the same as <code>Mean(variable)</code>! </p>
<div id="overview" class="section level2">
<h2>Overview</h2>
<p>The topics in this document are:</p>
<ul>
<li><p><a href="#packages">Packages</a></p></li>
<li><p><a href="#importing">Importing data sets</a></p></li>
<li><p><a href="#basertidy">Base R vs Tidyverse</a></p></li>
<li><p><a href="#datamanagement">Data management</a></p></li>
<li><p><a href="#graphs">Graphs</a></p></li>
<li><p><a href="#descriptives">Descriptives</a></p></li>
<li><p><a href="#tests">Statistical tests</a></p></li>
<li><p><a href="#regression">Regression</a></p></li>
<li><p><a href="#saving">Save your work</a></p></li>
</ul>
<p> </p>
</div>
<div id="packages" class="section level2">
<h2>Packages</h2>
<p>For a lot of R functions, additional libraries need to be loaded.</p>
<p>This can be done with:</p>
<pre class="r"><code>library(lattice)</code></pre>
<p>Sometimes the library needs to be installed first:</p>
<pre class="r"><code>install.packages(lattice)
library(lattice)</code></pre>
<p><em>Installing</em> a library only needs to be done once. <em>Loading</em> the library must be done every time you start R.</p>
<p>In the bottom right pane, you can find the tab <em>Packages</em>. Here you can find help on files about the packages. Help about a specific function can also be found with <code>?</code>:</p>
<pre class="r"><code>?xyplot</code></pre>
<p> </p>
</div>
<div id="importing" class="section level2">
<h2>Importing data sets</h2>
<p>How do I get my data in R?</p>
<div id="spss-file" class="section level4">
<h4>SPSS file</h4>
<ol style="list-style-type: decimal">
<li>Load the library foreign</li>
</ol>
<pre class="r"><code>library(foreign)</code></pre>
<ol start="2" style="list-style-type: decimal">
<li>Load data from spss using the function read.spss</li>
</ol>
<pre class="r"><code>data <- read.spss("C:/Documents/data.sav", to.data.frame = TRUE)</code></pre>
<p> </p>
</div>
<div id="excel-file" class="section level4">
<h4>Excel file</h4>
<ol style="list-style-type: decimal">
<li>Load the library readxl</li>
</ol>
<pre class="r"><code>library(readxl)</code></pre>
<ol start="2" style="list-style-type: decimal">
<li>Load data from spss using the function read_excel</li>
</ol>
<pre class="r"><code>data <- read_excel("C:/Documents/data.xlsx")</code></pre>
<p> </p>
<p><strong>Note 1</strong> For R to recognize the folder you need to use forward slashes (<code>/</code>) instead of backward slashes (<code>\</code>)</p>
<p><strong>Note 2</strong> Pay attention to the name you give your data set. You want it to be distinct, but don’t make it too long!</p>
<p> </p>
</div>
<div id="importing-data-with-the-menu" class="section level4">
<h4>Importing data with the menu</h4>
<p>Data can also be loaded via the menu. Go to File -> Import Dataset -> choose your filetype.</p>
<p> </p>
</div>
</div>
<div id="basertidy" class="section level2">
<h2>Base R vs Tidyverse</h2>
<p>Base is the base package in R, that contains a lot of the basic functions. Examples are <code>summary()</code> to get some summary statistics and <code>plot()</code> to make plots.</p>
<p>There exists a collection of packages, together called the Tidyverse, that allows you to do a lot of the base R things in a slightly different way. For example, the package <code>dplyr</code> is used for data management and with <code>ggplot()</code> you can make beautiful graphs. The Tidyverse has a bit of different style of coding (it has its own ‘grammar’) than most R functions.</p>
<p>Some people prefer working with their data with the Tidyverse, other prefer base R. In these tutorials, I will use base R for the data management and graphs in the <em>Getting Started</em> tutorials, and show some Tidyverse functions in the <em>Advanced options</em> tutorials.</p>
<p> </p>
<div id="small-example" class="section level4">
<h4>Small example</h4>
<p>In the two code chunks below, I demonstrate the difference between the two styles. The codes give the means of an outcome (weight of chickens) for different groups (feed type).</p>
<p>It is not necessary to understand the code yet! This example is just to demonstrate how two different pieces of code, give the same result.</p>
<p> </p>
<p>With base R</p>
<pre class="r"><code>data(chickwts)
aggregate(chickwts$weight, list(chickwts$feed), FUN=mean) </code></pre>
<pre><code>## Group.1 x
## 1 casein 323.5833
## 2 horsebean 160.2000
## 3 linseed 218.7500
## 4 meatmeal 276.9091
## 5 soybean 246.4286
## 6 sunflower 328.9167</code></pre>
<p> </p>
<p>With <code>dplyr</code> from the Tidyverse</p>
<pre class="r"><code>library(dplyr)
data(chickwts)
chickwts %>%
group_by(feed) %>%
summarize(Mean = mean(weight)) </code></pre>
<pre><code>## # A tibble: 6 x 2
## feed Mean
## <fct> <dbl>
## 1 casein 324.
## 2 horsebean 160.
## 3 linseed 219.
## 4 meatmeal 277.
## 5 soybean 246.
## 6 sunflower 329.</code></pre>
<p>The main difference between the styles, is that with the <code>dplyr</code> code, things elements of the code are added stepwise, whereas with the base R, everything is handled at the same time.</p>
<p> </p>
</div>
</div>
<div id="datamanagement" class="section level2">
<h2>Data management</h2>
<p>We want to investigate and explore the data set before we perform our analyses. Often we also need to perform some data manipulation steps first. </p>
<div id="explore-data" class="section level4">
<h4>Explore data</h4>
<p>Let’s explore a dataset.</p>
<p>We will use a standard data set available in R (mtcars). I will name this dataset “data”</p>
<pre class="r"><code>data(mtcars)
data <- mtcars</code></pre>
<p>With the function <code>head</code>, we can print the first couple of rows; check out the names of the variables and the first entries.</p>
<pre class="r"><code>head(data)</code></pre>
<pre><code>## mpg cyl disp hp drat wt qsec vs am gear carb
## Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
## Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
## Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
## Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
## Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1</code></pre>
<p> </p>
<div id="obtain-the-summaries-of-each-variable" class="section level5">
<h5>Obtain the summaries of each variable</h5>
<p>The numbers of missings <code>NA</code> are also reported.</p>
<pre class="r"><code>summary(data)</code></pre>
<pre><code>## mpg cyl disp hp
## Min. :10.40 Min. :4.000 Min. : 71.1 Min. : 52.0
## 1st Qu.:15.43 1st Qu.:4.000 1st Qu.:120.8 1st Qu.: 96.5
## Median :19.20 Median :6.000 Median :196.3 Median :123.0
## Mean :20.09 Mean :6.188 Mean :230.7 Mean :146.7
## 3rd Qu.:22.80 3rd Qu.:8.000 3rd Qu.:326.0 3rd Qu.:180.0
## Max. :33.90 Max. :8.000 Max. :472.0 Max. :335.0
## drat wt qsec vs
## Min. :2.760 Min. :1.513 Min. :14.50 Min. :0.0000
## 1st Qu.:3.080 1st Qu.:2.581 1st Qu.:16.89 1st Qu.:0.0000
## Median :3.695 Median :3.325 Median :17.71 Median :0.0000
## Mean :3.597 Mean :3.217 Mean :17.85 Mean :0.4375
## 3rd Qu.:3.920 3rd Qu.:3.610 3rd Qu.:18.90 3rd Qu.:1.0000
## Max. :4.930 Max. :5.424 Max. :22.90 Max. :1.0000
## am gear carb
## Min. :0.0000 Min. :3.000 Min. :1.000
## 1st Qu.:0.0000 1st Qu.:3.000 1st Qu.:2.000
## Median :0.0000 Median :4.000 Median :2.000
## Mean :0.4062 Mean :3.688 Mean :2.812
## 3rd Qu.:1.0000 3rd Qu.:4.000 3rd Qu.:4.000
## Max. :1.0000 Max. :5.000 Max. :8.000</code></pre>
<p> </p>
</div>
<div id="obtain-the-summaries-of-one-variable" class="section level5">
<h5>Obtain the summaries of one variable</h5>
<p>With the <code>$</code> symbol we access a variable in a data set.</p>
<pre class="r"><code>summary(data$mpg)</code></pre>
<pre><code>## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 10.40 15.43 19.20 20.09 22.80 33.90</code></pre>
<p> </p>
</div>
<div id="obtain-the-variable-names" class="section level5">
<h5>Obtain the variable names</h5>
<pre class="r"><code>names(data)</code></pre>
<pre><code>## [1] "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear"
## [11] "carb"</code></pre>
<p> </p>
</div>
<div id="look-at-the-type-of-variables-in-the-data" class="section level5">
<h5>Look at the type of variables in the data:</h5>
<p>Numeric - Factor - character - Integer - etc</p>
<pre class="r"><code>str(data)</code></pre>
<pre><code>## 'data.frame': 32 obs. of 11 variables:
## $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
## $ cyl : num 6 6 4 6 8 6 8 4 4 6 ...
## $ disp: num 160 160 108 258 360 ...
## $ hp : num 110 110 93 110 175 105 245 62 95 123 ...
## $ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
## $ wt : num 2.62 2.88 2.32 3.21 3.44 ...
## $ qsec: num 16.5 17 18.6 19.4 17 ...
## $ vs : num 0 0 1 1 0 1 0 1 1 1 ...
## $ am : num 1 1 1 0 0 0 0 0 0 0 ...
## $ gear: num 4 4 4 3 3 3 3 4 4 4 ...
## $ carb: num 4 4 1 1 2 1 4 2 2 4 ...</code></pre>
<p> </p>
</div>
</div>
<div id="basic-data-manipulation" class="section level4">
<h4>Basic data manipulation</h4>
<div id="rename-variables" class="section level5">
<h5>Rename variables</h5>
<pre class="r"><code>names(data)[names(data) == "carb"] <- "CARB"</code></pre>
<p> </p>
</div>
<div id="make-a-subset-of-your-data" class="section level5">
<h5>Make a subset of your data</h5>
<p><strong>Tip! </strong> Create a new data set with a new name. Otherwise you might lose important information in your data.</p>
<p>Remove observations with missings (<code>NA</code>) in “mpg” and “cyl”</p>
<pre class="r"><code>data2 <- subset(data, !is.na(data$mpg) & !is.na(data$cyl))</code></pre>
<p> </p>
</div>
<div id="remove-observation-above-a-certain-threshold" class="section level5">
<h5>Remove observation above a certain threshold</h5>
<p>Make a new dataset, including only mpg values > 20. (Don’t forget the comma in the code!)</p>
<pre class="r"><code>data2 <- data[data$mpg > 20, ]</code></pre>
<p> </p>
</div>
<div id="remove-duplicates" class="section level5">
<h5>Remove duplicates</h5>
<p>This can be used if there are multiple measurement per patient, but you want to keep only the first.</p>
<pre class="r"><code>data.short <- data[!duplicated(data$gear),]</code></pre>
<p> </p>
</div>
<div id="remove-variables" class="section level5">
<h5>Remove variables</h5>
<pre class="r"><code>data2 <- subset(data, select = -c(mpg, cyl))</code></pre>
<p> </p>
</div>
<div id="keep-variables" class="section level5">
<h5>Keep variables</h5>
<pre class="r"><code>data2 <- subset(data, select = c(mpg, cyl))</code></pre>
<p> </p>
<p>More options for data management can by found in the <a href="LearnR2.html#datamanagement2">Advanced options</a>. </p>
</div>
</div>
</div>
<div id="graphs" class="section level2">
<h2>Graphs</h2>
<p>Make a simple histogram (mpg = continuous variable)</p>
<pre class="r"><code>hist(data$mpg)</code></pre>
<p><img src="LearnR_files/figure-html/unnamed-chunk-22-1.png" width="672" /></p>
<p>Make a simple scatter plot (mpg & disp = continuous variables)</p>
<pre class="r"><code>plot(data$mpg ~ data$disp)</code></pre>
<p><img src="LearnR_files/figure-html/unnamed-chunk-23-1.png" width="672" /></p>
<p>Make a simple boxplot (mpg = continuous variable, cyl = categorical variable)</p>
<pre class="r"><code>boxplot(data$mpg ~ data$cyl)</code></pre>
<p><img src="LearnR_files/figure-html/unnamed-chunk-24-1.png" width="672" /></p>
<p>Improve the scatterplot by changing the color, adding a title, etc.</p>
<pre class="r"><code>plot(data$mpg ~ mtcars$disp, xlab = "Disp", ylab = "Mpg",
xlim = c(75, 475), ylim = c(10, 35),
main = "Scatterplot Mpg - Disp", col = "red", pch = 20, cex = 1.5)</code></pre>
<p><img src="LearnR_files/figure-html/unnamed-chunk-25-1.png" width="672" /></p>
<p>For two plots next to each other we can use the function <code>par(mfrow = c(1,2))</code></p>
<pre class="r"><code>par(mfrow = c(1,2))
plot(data$mpg ~ data$disp)
plot(data$mpg ~ mtcars$disp, xlab = "Disp", ylab = "Mpg",
xlim = c(75, 475), ylim = c(10, 35),
main = "Scatterplot Mpg - Disp", col = "red", pch = 20, cex = 1.5)</code></pre>
<p><img src="LearnR_files/figure-html/unnamed-chunk-26-1.png" width="672" /></p>
<p> To learn how to use ggplot2 for graphics, you can go to <a href="LearnR2.html#graphs2">Advanced graphs</a>.</p>
<p> </p>
</div>
<div id="descriptives" class="section level2">
<h2>Descriptives</h2>
<div id="obtain-descriptives-for-continuous-variables" class="section level5">
<h5>Obtain descriptives for continuous variables</h5>
<p>mean (sd)</p>
<pre class="r"><code>mean(data$mpg)</code></pre>
<pre><code>## [1] 20.09062</code></pre>
<pre class="r"><code>sd(data$mpg)</code></pre>
<pre><code>## [1] 6.026948</code></pre>
<p>median (IQR)</p>
<pre class="r"><code>median(data$mpg)</code></pre>
<pre><code>## [1] 19.2</code></pre>
<pre class="r"><code>quantile(data$mpg, probs = c(0.25, 0.75))</code></pre>
<pre><code>## 25% 75%
## 15.425 22.800</code></pre>
<p> </p>
</div>
<div id="obtain-descriptives-for-categorical-variables" class="section level5">
<h5>Obtain descriptives for categorical variables</h5>
<p>Frequencies</p>
<pre class="r"><code>table(data$cyl)</code></pre>
<pre><code>##
## 4 6 8
## 11 7 14</code></pre>
<p>Crosstabs</p>
<pre class="r"><code>table(data$cyl, data$vs)</code></pre>
<pre><code>##
## 0 1
## 4 1 10
## 6 3 4
## 8 14 0</code></pre>
<p> </p>
</div>
</div>
<div id="tests" class="section level2">
<h2>Statistical tests</h2>
<div id="t-test" class="section level4">
<h4>T-test</h4>
<p>With a t-test, we compare a normally distributed continuous variable between two groups. In the data “am” is a grouping variable (0/1). Let’s explore this variable with <code>table</code>:</p>
<pre class="r"><code>table(data$am)</code></pre>
<pre><code>##
## 0 1
## 19 13</code></pre>
<p>“drat” is a continuous variable. Is it normally distributed?</p>
<pre class="r"><code>par(mfrow = c(1,2))
hist(data$drat)
qqnorm(data$drat)
qqline(data$drat, col = "steelblue")</code></pre>
<p><img src="LearnR_files/figure-html/unnamed-chunk-32-1.png" width="672" /></p>
<p>This looks pretty normal, so we can use a t-test to analyze these data.</p>
<pre class="r"><code>t.test(drat ~ am, data = data)</code></pre>
<pre><code>##
## Welch Two Sample t-test
##
## data: drat by am
## t = -5.6461, df = 27.198, p-value = 5.267e-06
## alternative hypothesis: true difference in means between group 0 and group 1 is not equal to 0
## 95 percent confidence interval:
## -1.0411183 -0.4862501
## sample estimates:
## mean in group 0 mean in group 1
## 3.286316 4.050000</code></pre>
<p>The output provides us with the p-value of the test, but also the 95% confidence interval and the mean in both groups.</p>
<p>It is possible to save the test as an r object (named “test”) and extract the p-value from it.</p>
<pre class="r"><code>test <- t.test(drat ~ am, data = data)
test$p.value</code></pre>
<pre><code>## [1] 5.266742e-06</code></pre>
<p> </p>
</div>
<div id="mann-whitney-u-test" class="section level4">
<h4>Mann-Whitney U test</h4>
<p>When the continuous variable is not normally distributed, we use the Mann-Whitney U test (or Wilcoxon Rank Sum test). The variable “mpg” is not normally distributed as we can see by the graphs.</p>
<pre class="r"><code>par(mfrow = c(1,2))
hist(data$disp)
qqnorm(data$disp)
qqline(data$disp, col = "steelblue")</code></pre>
<p><img src="LearnR_files/figure-html/unnamed-chunk-35-1.png" width="672" /></p>
<p>So, we use the code <code>wilcox.test</code></p>
<pre class="r"><code>wilcox.test(disp ~ am, data = data)</code></pre>
<pre><code>##
## Wilcoxon rank sum test with continuity correction
##
## data: disp by am
## W = 214, p-value = 0.0005493
## alternative hypothesis: true location shift is not equal to 0</code></pre>
<p>The p-value is <0.05, so we can reject H0. </p>
</div>
<div id="anova" class="section level4">
<h4>ANOVA</h4>
<p>When we want to compare a continuous variable in more than 2 groups, we can use an ANOVA. For this test, we assume that the continuous marker follows a normal distribution. The variable “gear” has three groups:</p>
<pre class="r"><code>table(data$gear)</code></pre>
<pre><code>##
## 3 4 5
## 15 12 5</code></pre>
<p>We will use ANOVA to test if “drat” is similar over the “gear” groups. We visualize the data first:</p>
<pre class="r"><code>boxplot(data$drat ~ data$gear)</code></pre>
<p><img src="LearnR_files/figure-html/unnamed-chunk-38-1.png" width="672" /></p>
<p>There appears to be a big difference, especially in group 3. For the ANOVA procedure in R it is better if the grouping variable is a “factor” instead of “numeric”, so we make a new variable: gear.factor.</p>
<pre class="r"><code>str(data$gear)</code></pre>
<pre><code>## num [1:32] 4 4 4 3 3 3 3 4 4 4 ...</code></pre>
<pre class="r"><code>data$gear.factor <- as.factor(data$gear)
str(data$gear.factor)</code></pre>
<pre><code>## Factor w/ 3 levels "3","4","5": 2 2 2 1 1 1 1 2 2 2 ...</code></pre>
<pre class="r"><code>aov1 <- aov(drat ~ gear.factor, data = data)
summary(aov1)</code></pre>
<pre><code>## Df Sum Sq Mean Sq F value Pr(>F)
## gear.factor 2 6.133 3.0667 32.59 3.82e-08 ***
## Residuals 29 2.729 0.0941
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1</code></pre>
<p>The p-value is highly significant. We can perform a post-hoc test, to see which groups are different from each other. With Tukey we adjust the p-value to correct for multiple testing.</p>
<pre class="r"><code>TukeyHSD(aov1)</code></pre>
<pre><code>## Tukey multiple comparisons of means
## 95% family-wise confidence level
##
## Fit: aov(formula = drat ~ gear.factor, data = data)
##
## $gear.factor
## diff lwr upr p adj
## 4-3 0.9106667 0.6172574 1.2040759 0.0000001
## 5-3 0.7833333 0.3921210 1.1745457 0.0000856
## 5-4 -0.1273333 -0.5305858 0.2759191 0.7181847</code></pre>
<p>Group 3 is indeed different from 4 and 5. </p>
</div>
<div id="kruskal-wallis-test" class="section level4">
<h4>Kruskal-Wallis test</h4>
<p>The non-paramtric version of the ANOVA is the Kruskal-Wallis test.</p>
<pre class="r"><code>boxplot(data$disp ~ data$gear.factor)</code></pre>
<p><img src="LearnR_files/figure-html/unnamed-chunk-42-1.png" width="672" /></p>
<pre class="r"><code>kruskal.test(disp ~ gear.factor, data = data)</code></pre>
<pre><code>##
## Kruskal-Wallis rank sum test
##
## data: disp by gear.factor
## Kruskal-Wallis chi-squared = 16.578, df = 2, p-value = 0.0002513</code></pre>
<p>The groups of gear are also significantly different for disp values.</p>
<p> </p>
</div>
<div id="chi-squared-test" class="section level4">
<h4>Chi-squared test</h4>
<p>To see if two binary or categorical variables are associated, we can use the chi-squared test.</p>
<p>The variables “vs” and “am” are both binary. With <code>table()</code> we can make a crosstab of the variables.</p>
<pre class="r"><code>tab <- with(data, table(vs, am))
tab</code></pre>
<pre><code>## am
## vs 0 1
## 0 12 6
## 1 7 7</code></pre>
<p>We now estimate the chi-squared statistic on this table:</p>
<pre class="r"><code>chisq.test(tab)</code></pre>
<pre><code>##
## Pearson's Chi-squared test with Yates' continuity correction
##
## data: tab
## X-squared = 0.34754, df = 1, p-value = 0.5555</code></pre>
<p>The p-value is > 0.05.</p>
<p> </p>
</div>
<div id="correlations" class="section level4">
<h4>Correlations</h4>
<p>Correlations are used for two continuous variables. We already made a scatterplot of “mpg” and “disp”.</p>
<pre class="r"><code>plot(data$mpg ~ data$disp)</code></pre>
<p><img src="LearnR_files/figure-html/unnamed-chunk-46-1.png" width="672" /></p>
<p>There seems to be a strong negative correlation between the variables. Is it significant?</p>
<pre class="r"><code>cor.test(data$disp, data$mpg, method = "spearman")</code></pre>
<pre><code>##
## Spearman's rank correlation rho
##
## data: data$disp and data$mpg
## S = 10415, p-value = 6.37e-13
## alternative hypothesis: true rho is not equal to 0
## sample estimates:
## rho
## -0.9088824</code></pre>
<p>Since “mpg” is not normally distributed, we use the <code>method = "spearman"</code> version of the test. For the Pearson correlation, use <code>method = "pearson"</code>. The correlation is -0.9 and highly significant.</p>
<p> </p>
</div>
</div>
<div id="regression" class="section level2">
<h2>Regression</h2>
<p> </p>
<div id="linear-regression" class="section level4">
<h4>Linear regression</h4>
<p>In regression we like to explain how one variable (x) influences changes in a second variable (y). Let’s start with a scatterplot for “drat” and “disp”:</p>
<pre class="r"><code>plot(drat ~ disp, data = data)</code></pre>
<p><img src="LearnR_files/figure-html/unnamed-chunk-48-1.png" width="672" /> </p>
<p>With the regression model we can estimate how unit-value in x (disp) impact a change in y (drat): The model is estimated with <code>lm()</code>. <code>summary()</code> prints a summary of the model.</p>
<pre class="r"><code>m1 <- lm(drat ~ disp, data = data)
summary(m1)</code></pre>
<pre><code>##
## Call:
## lm(formula = drat ~ disp, data = data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.85409 -0.23642 0.01812 0.13112 0.99196
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 4.3034722 0.1447123 29.738 < 2e-16 ***
## disp -0.0030639 0.0005545 -5.526 5.28e-06 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.3826 on 30 degrees of freedom
## Multiple R-squared: 0.5044, Adjusted R-squared: 0.4879
## F-statistic: 30.53 on 1 and 30 DF, p-value: 5.282e-06</code></pre>
<p> </p>
<p>The p-value for disp is highly significant (5.2820217^{-6}). I can extract the coefficient table from this object: </p>
<pre class="r"><code>summary(m1)$coefficients</code></pre>
<pre><code>## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 4.303472222 0.1447123152 29.738120 8.065594e-24
## disp -0.003063904 0.0005544844 -5.525681 5.282022e-06</code></pre>
<p> </p>
<p>To trust the results of the model, we need to validate the assumptions. Normality and homoskedasticity of the residuals can be checked by making plots.</p>
<pre class="r"><code>par(mfrow = c(2,2))
plot(m1)</code></pre>
<p><img src="LearnR_files/figure-html/unnamed-chunk-51-1.png" width="672" /></p>
<p>We look mainly at the two upper plots. With the first we can check whether the residuals from a noisy cloud of points. The qq-plot in the second graph can show whether the residuals follow a normal distribution. No serious deviations here. </p>
<p>Multiple independent (x) variables can be added to the model.</p>
<pre class="r"><code>m2 <- lm(drat ~ disp + mpg + vs, data = data)
summary(m2)</code></pre>
<pre><code>##
## Call:
## lm(formula = drat ~ disp + mpg + vs, data = data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.69295 -0.22024 -0.00385 0.18727 0.95692
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 3.665518 0.659203 5.561 6.01e-06 ***
## disp -0.002419 0.001122 -2.156 0.0398 *
## mpg 0.028263 0.021714 1.302 0.2037
## vs -0.179902 0.195797 -0.919 0.3660
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.3813 on 28 degrees of freedom
## Multiple R-squared: 0.5405, Adjusted R-squared: 0.4913
## F-statistic: 10.98 on 3 and 28 DF, p-value: 6.117e-05</code></pre>
<p> </p>
<p>Interactions can be added by using the <code>*</code> instead of the <code>+</code></p>
<pre class="r"><code>m3 <- lm(drat ~ disp * vs + mpg, data = data)
summary(m3)</code></pre>
<pre><code>##
## Call:
## lm(formula = drat ~ disp * vs + mpg, data = data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -0.59639 -0.20250 -0.05495 0.15378 0.94027
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 3.984823 0.653679 6.096 1.64e-06 ***
## disp -0.002403 0.001074 -2.236 0.0338 *
## vs 0.524636 0.418971 1.252 0.2212
## mpg 0.008746 0.023239 0.376 0.7096
## disp:vs -0.004128 0.002195 -1.880 0.0709 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.3652 on 27 degrees of freedom
## Multiple R-squared: 0.5937, Adjusted R-squared: 0.5336
## F-statistic: 9.865 on 4 and 27 DF, p-value: 4.718e-05</code></pre>
<p>Do not forget to evaluate the assumptions!</p>
<p> </p>
</div>
<div id="logistic-regression" class="section level4">
<h4>Logistic regression</h4>
<p>If the dependent variable is binary, we use a logistic regression model with <code>glm()</code></p>
<pre class="r"><code>glm1 <- glm(vs ~ drat, data = data, family = binomial(logit))
summary(glm1)</code></pre>
<pre><code>##
## Call:
## glm(formula = vs ~ drat, family = binomial(logit), data = data)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.7808 -0.7719 -0.6192 1.0357 2.0465
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -7.4480 3.1805 -2.342 0.0192 *
## drat 1.9875 0.8663 2.294 0.0218 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 43.860 on 31 degrees of freedom
## Residual deviance: 37.159 on 30 degrees of freedom
## AIC: 41.159
##
## Number of Fisher Scoring iterations: 3</code></pre>
<p> </p>
<p>The value of the coefficient is interpreted by taking the exponent</p>
<pre class="r"><code>b1 <- summary(glm1)$coef[2, 1]
exp(b1)</code></pre>
<pre><code>## [1] 7.297034</code></pre>
<p> </p>
<p>Multiple variables can be added to the model</p>
<pre class="r"><code>glm2 <- glm(vs ~ drat + am + mpg, data = data, family = binomial(logit))
summary(glm2)</code></pre>
<pre><code>##
## Call:
## glm(formula = vs ~ drat + am + mpg, family = binomial(logit),
## data = data)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.22751 -0.40730 -0.08654 0.28217 1.67256
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -16.1227 6.4962 -2.482 0.0131 *
## drat 1.3874 1.7037 0.814 0.4154
## am -3.6872 1.8619 -1.980 0.0477 *
## mpg 0.6176 0.2541 2.431 0.0151 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 43.860 on 31 degrees of freedom
## Residual deviance: 19.956 on 28 degrees of freedom
## AIC: 27.956
##
## Number of Fisher Scoring iterations: 6</code></pre>
<p> </p>
<p>The predicted probability of ‘vs’ for specific values of the x variables can be calculated with <code>predict()</code></p>
<pre class="r"><code>DF <- data.frame(drat = 3.6, am = 1, mpg = 20.1)
predict(glm2, newdata = DF, type = "response")</code></pre>
<pre><code>## 1
## 0.08303771</code></pre>
<p>The option <code>type = "response"</code> ensure the result is given als probability.</p>
<p> </p>
</div>
</div>
<div id="saving" class="section level2">
<h2>Saving your work</h2>
<p>There are several ways to save your work. </p>
<div id="save-script." class="section level4">
<h4>Save script.</h4>
<p>I always save my script as <code>.R</code> file. Additionally I can save separate R objects with the <code>save()</code> function.</p>
<p> </p>
</div>
<div id="save-datasets-and-output" class="section level4">
<h4>Save datasets and output</h4>
<p>If <code>data2</code> is the result of several datamanagement steps and the dataset that is used for the analyses, I might want to save data. I can save this as <code>.RData</code> file.</p>
<pre class="r"><code>save(data2, file = "C:/Documents/data2.RData")</code></pre>
<p><strong>Reminder note </strong> for R to recognize the folder you need to use forward slashes (<code>/</code>) instead of backward slashes (<code>\</code>)</p>
<p>Models that take a long time to run, can also be save in this way.</p>
<pre class="r"><code>save(Model1, file = "C:/Documents/model1.RData")</code></pre>
<p> </p>
</div>
<div id="export-data" class="section level4">
<h4>Export data</h4>
<p>If I want to use my data in excel, I can export the data to excel for example.</p>
<pre class="r"><code>library("xlsx")
save(data2, file = "C:/Documents/data2.xlsx")</code></pre>
<p> </p>
</div>
<div id="save-graphs" class="section level4">
<h4>Save graphs</h4>
<p>Graphs can be saved in different file formats use <code>png(), pdf(), tiff() etc.</code> to create the file. Then run the code for the plot. With <code>dev.off()</code> at the end, the plot is saved as the file.</p>
<pre class="r"><code>png("C:/Documents/plots.png")
plot(data$mpg ~ mtcars$disp, xlab = "Disp", ylab = "Mpg")
dev.off()</code></pre>
<p> </p>
</div>
<div id="save-environment" class="section level4">
<h4>Save environment</h4>
<p>You can also save the whole environment you are working in:</p>
<pre class="r"><code>save.image(file = "C:/Documents/MyEnvironment.RData")</code></pre>
</div>
</div>