-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0Hands-On-Exercise0.Rmd
932 lines (660 loc) · 22.3 KB
/
0Hands-On-Exercise0.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
---
title: "Quantitative Research Skills 2022, Hands-On Exercise 0"
subtitle: "Getting started with RStudio and R Markdown, visualisation, data wrangling"
author: "Rong Guang"
date: "14092022"
output:
html_document:
theme: flatly
highlight: haddock
toc: true
toc_depth: 2
number_section: false
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Hands-On Exercise 0: Getting started with RStudio and R Markdown, visualisation, data wrangling
This R Markdown sheet includes a quite large set of R code chunks taken from the RHDS book
**R for Health Data Science** by Ewen Harrison and Riinu Pius (CRC Press, 2021), available online at https://argoshare.is.ed.ac.uk/healthyr_book/.
The structure here follows the structure of the book (chapters, sections and subsections).
*******************************************************************************
# RHDS Chapter 1: Why we love R
You should begin by reading (or browsing through) this chapter from the RHDS book:
https://argoshare.is.ed.ac.uk/healthyr_book/why-we-love-r.html
**Note1:** On this QRS course, we focus on writing the steps of the analysis in R Markdown. R scripts that are also used in the RHDS book are a bit simpler, but these R Markdown sheets are often more useful.
**Note2:** We have already copy-pasted many of the R codes from the RHDS book for you in this R Markdown sheet. Your task is to run those codes and analyse their outputs - or copy more code from the book. We have also included the example datasets of RHDS book using links to our GitHub repository, so all the datasets of the book are easily accessible on the fly, without a need to download them separately.
The following is the first example of an **R code chunk**, where you can activate R functions. Its contents have been copy-pasted from Section 1.7. Try now to activate the R "command" ("1001:1004") by putting the cursor on that line below, and pressing Ctrl+Enter (on Windows) or Cmd+Enter (on Mac)!
```{r}
library(knitr)
# Now we're printing bigger numbers:
1001:1004
```
As you see above, the results (in this case, the numbers 1001, 1002, 1003, and 1004) appear immediately below the R code chunk (preceded by the usual [1], which you will also get used to, very soon.)
OK, as soon as you have read Chapter 1, you are ready to move on!
*******************************************************************************
We will begin the actual studying of the RHDS book from **Chapter 4**, in order to create some nice visualisations!
# RHDS Chapter 4: Different types of plots
In this assignment, you should explore (most of) Chapter 4 of the RHDS book, reading the contents and creating the graphs. In the end you should have tried a good set of different R graphs. This is where you start!
You can easily copy the R code from the book (use the one-click method "Copy to clipboard" in the upper-right corners of the R code boxes!)
https://argoshare.is.ed.ac.uk/healthyr_book/chap04-h1.html
Please follow the given structure below (the book sections) and continue similarly. Have fun! :)
## 4.1 Get the data
In order to draw Figure 4.1 step-by-step, we of course need the data! Here, we will use the famous Gapminder data that is available as an R package.
So, you may have to install the tidyverse and gapminder packages first. Then you must call the 'library' functions that will open those packages for use.
**Remember:** activate one line by Ctrl+Enter (on Windows) or Cmd+Enter (on Mac). The results will be seen below the R code chunk (the gray area).
```{r}
# copied from https://argoshare.is.ed.ac.uk/healthyr_book/chap04-data.html
library(tidyverse)
library(gapminder)
library(patchwork)
glimpse(gapminder)
# continue with the code given on the same page and follow what has been done there!
gapminder$year %>% unique()
gapminder$country %>% n_distinct()
gapminder$continent %>% unique()
gapdata2007 <- gapminder %>%
filter(year == 2007)
gapdata2007
gapdata <- gapminder
```
## 4.2 Anatomy of ggplot explained
Here, we begin plotting the data step-by-step!
https://argoshare.is.ed.ac.uk/healthyr_book/chap04-gganatomy.html
In addition to activating R functions in this editor, try also **knitting** this document to an HTML report (webpage)!
```{r}
# LOT of R code in that section (4.2)!
# Copy all code here, piece by piece, and try each one to see what happens!
# (you may also create additional R code chunks below - no need to put all code in one chunk!)
gapdata2007 %>%
ggplot(aes(x = gdpPercap, y = lifeExp))
```
```{r}
ggplot(gapdata2007, aes(x = gdpPercap, y = lifeExp))
```
```{r}
gapdata2007 %>%
ggplot(aes(x = gdpPercap, y = lifeExp)) +
geom_point()
```
```{r}
gapdata2007 %>%
ggplot(aes(x = continent, y = lifeExp)) +
geom_point()
```
```{r}
gapdata2007 %>%
ggplot(aes(x = gdpPercap, y = lifeExp, colour = continent)) +
geom_point()
```
```{r}
gapdata2007 %>%
ggplot(aes(x = gdpPercap, y = lifeExp, colour = continent)) +
geom_point(shape = 1)
```
```{r}
gapdata2007 %>%
ggplot(aes(x = gdpPercap, y = lifeExp, colour = continent)) +
geom_point(shape = 1) +
facet_wrap(~continent)
```
```{r}
gapdata2007 %>%
ggplot(aes(x = gdpPercap, y = lifeExp, colour = continent)) +
geom_point(shape = 1) +
facet_wrap(~pop > 50000000)
```
```{r}
gapdata2007 %>%
ggplot(aes(x = gdpPercap/1000, y = lifeExp, colour = continent)) +
geom_point(shape = 23) +
facet_wrap(~continent) +
theme_bw()
```
## 4.3 Set your theme - grey vs white
```{r}
# continue similarly, copying the R code and working with it step-by-step!
# (remember to save this document from time to time!)
theme_set(theme_bw())
gapdata2007 %>%
ggplot(aes(x = gdpPercap, y = lifeExp, colour = continent)) +
geom_point(shape = 1) +
facet_wrap(~pop > 10000000)
```
## 4.4 Scatter plots/bubble plots
```{r}
a1 <- gapdata2007 %>%
ggplot(aes(x = gdpPercap/1000, y = lifeExp, size = pop)) +
geom_point(shape = 1, alpha = 0.5) +
theme(legend.position = "none")
a2 <- gapdata %>%
filter (country == "United Kingdom") %>%
ggplot (aes(x = year, y = lifeExp)) +
geom_line()
a3 <- gapdata %>%
ggplot(aes(x = year, y = lifeExp, group = country, color = continent)) +
geom_line() +
facet_wrap (~continent) +
scale_colour_brewer(palette = "Paired")+
theme(legend.position = "none")
a1/a2|a3
```
```{r}
# continue the work...
# perhaps try to knit this, too, to see the web page that gathers everything you have done so far!
gapdata2007 %>%
ggplot(aes(x = gdpPercap/1000, y = lifeExp, size = pop)) +
geom_point()
```
```{r}
gapdata2007 %>%
ggplot(aes(x = gdpPercap/1000, y = lifeExp, size = pop)) +
geom_point(shape = 1, alpha = 0.5)
```
## 4.5 Line plots/time series plots
```{r}
gapdata %>%
filter(country == "United Kingdom") %>%
ggplot(aes(x = year, y = lifeExp)) +
geom_line()
```
```{r}
gapdata %>%
ggplot(aes(x = year, y = lifeExp)) +
geom_line()
```
```{r}
gapdata %>%
ggplot(aes(x = year, y = lifeExp, group=country)) +
geom_line()
```
```{r}
gapdata %>%
ggplot(aes(x = year, y = lifeExp, group=country, colour = continent)) +
geom_line() +
facet_wrap(~continent) +
scale_colour_brewer(palette = "Paired")
```
## 4.6 Bar plots
```{r}
# continue the work...
a4 <- gapdata2007 %>%
filter (country %in% c("United Kingdom", "France", "Germany")) %>%
ggplot (aes(x = country, y = lifeExp)) +
geom_col ()
a5 <- gapdata2007 %>%
filter (country %in% c("United Kingdom", "France", "Germany")) %>%
ggplot (aes(x= country, y = lifeExp)) +
geom_col() +
coord_cartesian (ylim = c(79, 81))
a4|a5
```
```{r}
gapdata2007 %>%
count(continent)
```
```{r}
a6 <- gapdata2007 %>%
ggplot(aes(x = continent)) +
geom_bar(fill = "lavender", alpha = 0.99)
a7 <- gapdata2007 %>%
ggplot (aes(x = continent, colour = country)) +
geom_bar(fill = NA) +
theme(legend.position = "none")
#scale_color_brewer (palette = "Paired") #why doesn't it work here?
a6|a7
```
```{r}
gapdata2007 %>%
ggplot(aes(x = "Global", fill = continent)) +
geom_bar(width = 0.2, colour = "white", size = 0.2)
```
```{r}
gapdata2007 %>%
filter (continent == "Europe") %>%
ggplot (aes(x = fct_reorder(country, lifeExp), y = lifeExp)) +
geom_col(fill = NA, colour = "deepskyblue", size = 0.2)+
coord_flip()
```
## 4.7 Histograms
```{r}
# continue the work...
histo1 <- gapdata2007 %>%
ggplot (aes(x = lifeExp)) +
geom_histogram (binwidth = 10)
histo2 <- gapdata %>%
ggplot (aes(x = lifeExp)) +
geom_histogram (binwidth = 10, fill = "deepskyblue", colour = "deepskyblue", size = 0.2, alpha = 0.5)
histo3 <- gapdata2007 %>%
ggplot (aes(x = lifeExp)) +
geom_histogram ()
histo1/histo3 | histo2
```
## 4.8 Box plots
```{r}
# continue the work...
gapdata2007 %>%
ggplot (aes(x = continent, y = lifeExp)) +
geom_boxplot()+
facet_wrap (~pop > 10000000)
glimpse(gapdata2007)
```
## 4.9 Multiple geoms, multiple aes()
```{r}
# continue the work... this is the last section required!
multi1 <- gapdata2007 %>%
ggplot (aes(x = continent, y = lifeExp)) +
geom_boxplot () +
geom_point() +
xlab("")
multi2 <- gapdata2007 %>%
ggplot (aes(x = continent, y = lifeExp)) +
geom_boxplot () +
geom_jitter ()
multi3 <- gapdata2007 %>%
ggplot (aes(x = continent, y = lifeExp, colour = continent)) +
geom_boxplot() +
geom_jitter() +
theme (legend.position = "none") +
xlab ("")+
ylab("")
multi4 <- gapdata2007 %>%
ggplot (aes(x = continent, y = lifeExp)) +
geom_boxplot() +
geom_jitter(aes(colour = continent)) +
theme(legend.position = "none") +
ylab("")
multi1/multi2|multi3/multi4
```
```{r}
label_data <- gapdata2007 %>%
group_by (continent) %>%
filter (lifeExp == max(lifeExp)) %>%
select (country, continent, lifeExp)
label_data
multi5 <- gapdata2007 %>%
ggplot(aes(x = continent, y = lifeExp)) +
geom_boxplot() +
geom_jitter(aes(colour = continent)) +
geom_label (data = label_data, aes (label = country)) +
theme (legend.position = "none")
multi6 <- gapdata2007 %>%
ggplot(aes(x = continent, y = lifeExp)) +
geom_boxplot() +
geom_jitter(aes(colour = continent)) +
geom_text (data = label_data, aes (label = lifeExp)) +
theme (legend.position = "none")
multi5|multi6
```
**Good job!**
You will now continue with the RHDS Chapter 2. This time we have already copy-pasted the required R code from the book. Your task is to actively go through all the sections below, activate the R functions and study their results. It may be a good idea to start also writing your own notes about things you may wonder - in this very same R Markdown sheet.
Brief instructions for the next steps towards **Assignment 0** are waiting for you in the end. Have fun!
*******************************************************************************
# RHDS Chapter 2: R basics
Again, the idea is that you read (or at least browse) the contents of the book while following the work flow (the R code chunks that have been created here for you).
So, begin reading at https://argoshare.is.ed.ac.uk/healthyr_book/r-basics.html.
As soon as you see R code in the book, look at your RStudio, in this R Markdown sheet. Activate the R functions one at a time and see what happens. Write your own notes freely (for example, if you do not understand some part of the code, write some notes about it).
## 2.1 Reading data into R
```{r}
library(tidyverse)
example_data <- read_csv("https://raw.githubusercontent.com/KimmoVehkalahti/RHDS/master/example_data.csv")
example_data # look at the data (and then come back here - you may also close the data view)
```
### 2.1.2 Reading in the Global Burden of Disease example dataset
```{r}
library(tidyverse)
gbd_short <-read_csv("https://raw.githubusercontent.com/KimmoVehkalahti/RHDS/master/data/global_burden_disease_cause-year.csv")
View(gbd_short)
label_death <- gbd_short %>%
mutate (deaths_millions = deaths_millions+3)
label_death
disease1 <- gbd_short %>%
ggplot(aes(x = year, y = deaths_millions, colour = cause))+
geom_line() +
facet_wrap (~cause) +
geom_point() +
theme(legend.position = "none") +
ylab("DeathPerYear (Millions)") +
xlab("") +
geom_text (data = label_death, aes(label = deaths_millions), size =2)
disease2 <- gbd_short %>%
ggplot (aes(x = factor(year), y = deaths_millions, colour = cause, fill = cause)) +
geom_col (width = 0.5) +
theme (legend.position = "none") +
coord_cartesian (ylim = c(20, 60))
disease1/disease2
```
## 2.2 Variable types and why we care
**Note:** Some outputs may differ a bit from the book, because R is constantly developed further. One example is the following. (We have modified the code chunk a bit to reveal the outputs shown in the book.)
```{r}
library(tidyverse)
typesdata <- read_csv("https://raw.githubusercontent.com/KimmoVehkalahti/RHDS/master/data/typesdata.csv")
spec(typesdata)
typesdata
```
```{r}
typesdata_faulty <- read_csv("https://raw.githubusercontent.com/KimmoVehkalahti/RHDS/master/data/typesdata_faulty.csv")
spec(typesdata_faulty)
typesdata_faulty
```
### 2.2.1 Numeric variables (continuous)
```{r}
typesdata$measurement %>% mean()
measurement_mean <- typesdata$measurement %>% mean()
measurement_mean == 3.333333
(0.10 + 0.05) == 0.15
library(tidyverse)
near(0.10+0.05, 0.15)
near(measurement_mean, 3.333333, 0.000001)
near (measurement_mean, 3.33333333)
```
### 2.2.2 Character variables
```{r}
library(tidyverse)
typesdata
typesdata %>%
count(group)
typesdata %>%
count(group, sort = TRUE)
# all ids are unique:
typesdata %>%
count(id, sort = TRUE)
# we add in a duplicate row where id = ID3,
# then count again:
typesdata %>%
add_row(id = "ID3") %>%
count(id, sort = TRUE)
typesdata
typesdata1 <- add_row(typesdata, id="ID3", group="Treatment")
typesdata1
```
### 2.2.3 Factor variables (categorical)
(just read - more about this topic will follow later...)
### 2.2.4 Date/time variables
```{r}
#Dear professor, I came across the problem that as long as I kept these codes relating to “lubricate”, the file will always not successfully save. I have no choice but turned them into notes for now. But I am sure that I have been clear about how these codes work.
#install.packages("lubridate")
#library(lubridate) # lubridate makes working with dates easier
#current_datetime <- Sys.time()
#current_datetime
#my_datetime <- "2020-12-01 12:00"
#my_datetime
#my_datetime - current_datetime
#current_datetime %>% class()
#my_datetime %>% class()
```
2.2.4 continued...
```{r}
#Dear professor, I came across the problem that as long as I kept these codes relating to “lubricate”, the file will always not successfully save. I have no choice but turned them into notes for now. But I am sure that I have been clear about how these codes work.
#install.packages("lubridate")
#library("lubridate")
#my_datetime_converted <- ymd_hm(my_datetime)
#my_datetime_converted
#my_datetime_converted - current_datetime
#my_datesdiff <- my_datetime_converted - current_datetime
#my_datesdiff %>% class()
#ymd_hm("2021-01-02 12:00") + my_datesdiff
#560/my_datesdiff
#560/as.numeric(my_datesdiff)
```
2.2.4 continued...
```{r}
#Dear professor, I came across the problem that as long as I kept these codes relating to “lubricate”, the file will always not successfully save. I have no choice but turned them into notes for now. But I am sure that I have been clear about how these codes work.
#parse_date_time("12:34 07/Jan'20", "%H:%M %d/%b'%y")
#Sys.time()
#Sys.time() %>% format("%H:%M on %B-%d (%Y)")
#Sys.time() %>% format("Happy days, the current time is %H:%M %B-%d (%Y)!")
```
## 2.3 Objects and functions
```{r}
library(tidyverse)
mydata <- tibble(
id = 1:4,
sex = c("Male", "Female", "Female", "Male"),
var1 = c(4, 1, 2, 3),
var2 = c(NA, 4, 5, NA),
var3 = c(2, 1, NA, NA)
)
```
### 2.3.1 data frame/tibble
### 2.3.2 Naming objects
```{r}
mydata
```
### 2.3.3 Function and its arguments
```{r}
mydata$var1
mean(mydata$var1)
mean(mydata$var2)
mean(mydata$sex)
mean(mydata$var2, na.rm = TRUE)
Sys.time()
```
### 2.3.4 Working with objects
```{r}
a <- 103
a
seq(15, 30)
example_sequence <- seq(15, 30)
example_sequence <- example_sequence/2
example_sequence
```
### 2.3.5 <- and =
```{r}
mean_result <- mean(mydata$var2, na.rm = TRUE)
mean_result
```
### 2.3.6 Recap: object, function, input, argument
## 2.4 Pipe - %>%
```{r}
library(tidyverse)
mydata$var1 %>% mean()
mean_result <- mydata$var1 %>% mean()
mean_result
```
### 2.4.1 Using . to direct the pipe
```{r}
mydata %>%
lm(var1~var2, data = .)
```
## 2.5 Operators for filtering data
```{r}
gbd_short %>%
filter(year < 1995)
gbd_short %>%
filter(year <= 1995)
gbd_short %>%
filter(year == 1995)
```
2.5 continued...
```{r}
gbd_short %>%
filter(year <= 1995)
gbd_short %>%
filter(year == 1995 | year == 2017)
gbd_short %>%
filter(year == max(year) | year == min(year))
```
### 2.5.1 Worked examples
```{r}
mydata_year2000 <- gbd_short %>%
filter(year == 2000)
mydata_year2000
```
2.5.1 continued...
```{r}
new_data_selection <- gbd_short %>%
filter((year == 1990 | year == 2013) & cause == "Communicable diseases")
new_data_selection
```
2.5.1 continued...
```{r}
# Or we can get rid of the extra brackets around the years
# by moving cause into a new filter on a new line:
new_data_selection <- gbd_short %>%
filter(year == 1990 | year == 2013) %>%
filter(cause == "Communicable diseases")
new_data_selection
```
2.5.1 continued...
```{r}
# Or even better, we can include both in one filter() call, as all
# separate conditions are by default joined with "&":
new_data_selection <- gbd_short %>%
filter(year == 1990 | year == 2013,
cause == "Communicable diseases")
new_data_selection
```
## 2.6 The combine function: c()
```{r}
gbd_short$cause %>% unique()
class(gbd_short$cause)
gbd_short %>% count(cause)
gbd_short %>%
# also filtering for a single year to keep the result concise
filter(year == 1990) %>%
filter(cause == "Communicable diseases" | cause == "Non-communicable diseases")
gbd_short %>%
filter(year == 1990) %>%
filter(cause %in% c("Communicable diseases", "Non-communicable diseases"))
```
## 2.7 Missing values (NAs) and filters
```{r}
mydata
mydata %>%
filter(is.na(var2))
mydata %>%
filter(!is.na(var2))
mydata %>%
filter(var2 != 5) %>%
knitr::kable()
mydata %>%
filter(var2 != 5 | is.na(var2)) %>%
knitr::kable()
```
2.7 continued...
```{r}
subset1 <- mydata %>%
filter(var2 == 5)
subset2 <- mydata %>%
filter(! var2 == 5)
subset1; subset2
nrow(mydata)
nrow(subset1)
nrow(subset2)
nrow(subset1) + nrow(subset2) == nrow(mydata)
subset3 <- mydata %>%
filter(is.na(var2))
subset3
nrow(subset1) + nrow(subset2) + nrow(subset3) == nrow(mydata)
```
## 2.8 Creating new columns - mutate()
```{r}
typesdata
typesdata$measurement
typesdata$measurement/2
typesdata %>%
mutate(measurement/2)
typesdata %>%
mutate(measurement_half = measurement/2)
```
2.8 continued...
```{r}
#Dear professor, I came across the problem that as long as I kept these codes relating to “Nasty column name”, the file will always not successfully save. I have no choice but turned them into notes for now. But I am sure that I have been clear about how these codes work.
#mydata$`Nasty column name`
#mydata
# or
#mydata %>%
#select(`Nasty column name`)
```
2.8 continued...
```{r}
typesdata_modified <- typesdata %>%
mutate(measurement_half = measurement/2)
typesdata_modified
```
2.8 continued...
```{r}
library(lubridate)
typesdata
typesdata %>%
mutate(reference_date = ymd_hm("2020-01-01 12:00"),
dates_difference = reference_date - date) %>%
select(date, reference_date, dates_difference)
typesdata %>%
mutate(mean_measurement = mean(measurement))
typesdata %>%
mutate(mean_measurement = mean(measurement)) %>%
mutate(measurement_relative = measurement/mean_measurement) %>%
select(matches("measurement"))
```
### 2.8.1 Worked example/exercise
```{r}
typesdata %>%
mutate(reference_date = ymd_hm("2020-01-01 12:00"),
dates_difference = reference_date - date) %>%
mutate(dates_difference = round(dates_difference)) %>%
select(matches("date"))
typesdata %>% select(matches("date"))
```
## 2.9 Conditional calculations - if_else()
```{r}
typesdata %>%
mutate(above_threshold = if_else(measurement > 3,
"Above three",
"Below three"))
```
```{r}
a <- tibble(number = c(1,2,3,2,5,10,25,12,23,7,9))
a
a %>% mutate(number_level = ifelse(
number <= 10, "low", ifelse(
number <= 20, "middle", "high"))) #nested ifelse
```
## 2.10 Create labels - paste()
```{r}
typesdata %>%
mutate(plot_label = paste(id,
"was last measured at", date,
", and the value was", measurement)) %>%
select(plot_label)
pastedata <- tibble(year = c(2007, 2008, 2009),
month = c("Jan", "Feb", "March"),
day = c(1, 2, 3))
pastedata
```
2.10 continued...
```{r}
pastedata %>%
mutate(date = paste(day, month, year, sep = "/"))
library(lubridate)
pastedata %>%
mutate(date = paste(day, month, year, sep = "-")) %>%
mutate(date = dmy(date))
```
## 2.11 Joining multiple datasets
```{r}
library(tidyverse)
patientdata <- read_csv("https://raw.githubusercontent.com/KimmoVehkalahti/RHDS/master/data/patient_data.csv")
patientdata
labsdata <- read_csv("https://raw.githubusercontent.com/KimmoVehkalahti/RHDS/master/data/labs_data.csv")
labsdata
full_join(patientdata, labsdata)
inner_join(patientdata, labsdata)
left_join(patientdata, labsdata)
right_join(patientdata, labsdata)
```
### 2.11.1 Further notes about joins
```{r}
patientdata_new <- read_csv("https://raw.githubusercontent.com/KimmoVehkalahti/RHDS/master/data/patient_data_updated.csv")
patientdata_new
bind_rows(patientdata, patientdata_new)
labsdata_updated <- labsdata %>%
add_row(id = 5, measurement = 2.49)
labsdata_updated
left_join(patientdata, labsdata_updated)
```
**Well done! That was active reading of Chapter 2.**
You have now completed the Hands-On Exercise 0. **GOOD JOB!**
Your next task is to download and work through **Assignment 0**. You will need the information above, so it is a good idea to keep this file open too, while you are working with the Assignment.
</pre></body></html>_text/x-markdownUUTF-8