-
Notifications
You must be signed in to change notification settings - Fork 25
/
06-workshop_dplyr.Rmd
926 lines (577 loc) · 17.1 KB
/
06-workshop_dplyr.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
---
title: "Data wrangling with dplyr"
subtitle: "Session 6"
institute: "NHS-R Community"
output:
xaringan::moon_reader:
css:
- default
- css/nhsr.css
- css/nhsr-fonts.css
lib_dir: libs
seal: false
self_contained: true
nature:
highlightStyle: googlecode
highlightLines: true
highlightLanguage: ["r"]
countIncrementalSlides: false
ratio: "16:9"
includes:
after_body: [css/insert-logo.html]
---
```{r libs, include=FALSE}
library(knitr)
library(magick)
library(tidyverse)
library(xaringan)
library(kableExtra)
library(icons)
library(xaringanExtra)
xaringanExtra::use_panelset()
xaringanExtra::use_clipboard()
xaringanExtra::use_share_again() # need to get the slide button on html view
opts_chunk$set(
echo = TRUE,
eval = FALSE,
message = FALSE,
warning = FALSE,
fig.width = 7.252,
fig.height = 4,
dpi = 300,
dev.args = list(type = "cairo")
)
# Load data -----------------------------------
beds_data <- read_csv(url("https://raw.githubusercontent.com/nhs-r-community/intro_r_data/main/beds_data.csv"), col_types = cols(date = col_date(format = "%d/%m/%Y")),
skip = 3)
```
class: title-slide, left, bottom
<img src="img/session06/dplyr_wrangling.PNG" width="40%"/>
# `r rmarkdown::metadata$title`
----
## **`r rmarkdown::metadata$subtitle`**
### `r rmarkdown::metadata$author`
### `r rmarkdown::metadata$date`
.right-column[
]
.footnote[Artwork by @allison_horst]
---
class: center, middle
# Wrangling
</br> Reshaping or transforming data
</br> into a format which is easier to work with
</br> (…for later visualisation, modelling,
</br> or computing of statistics…)
---
# A note on "tidy" data
Tidyverse functions work best with tidy data:
1. Each variable forms a column.
2. Each observation forms a row.
</br> (Broadly, this means long rather than wide tables)
---
class: center, middle
# The tool: dplyr package
.blue[(dee-ply-r)]
is a language for data manipulation </br>
</br> Most wrangling puzzles can be solved with
</br> knowledge of just 5 dplyr verbs .blue[(5 functions)]. </br>
</br> These verbs will be the subject of this session.
---
# Project 2:
## Exploring Mental Health (MH) Inpatient Capacity
--
</br> The following is some analysis of Mental Health inpatient capacity in England.
</br> As part of this, we will be looking at the changes in the number (and occupancy) of MH beds available.
--
### Background
Maintaining clinical effectiveness and safety when a
ward is fully occupied is a serious challenge for staff.
</br> Inappropriate out of area placements have an added cost and also mean
patients are separated from their social support networks.
---
# The Data:
</br> KH03 returns (bed numbers and occupancy) by organisation, published by NHS England.
</br> Scraped from the NHSE statistics website:
</br> https://www.england.nhs.uk/statistics/statistical-work-areas/bed-availability-and-occupancy/bed-data-overnight/
.blue[partially cleaned]
---
# Start a new script
File/New script or shortcut keys <kbd>Ctrl + Shift + N </kbd>
.left-column[
Load the data
beds_data.csv
]
.right-column[
<img class="center" src="img/session06/new-script.PNG"/>
]
---
# Less friendly csvs
<img class="center" src="img/session06/beds-data-wizard.PNG"/>
---
# Less friendly csvs
<img class="center" src="img/session06/beds-data-wizard-2.png"/>
---
# Less friendly csvs
Note you will have to move the cursor to another area for the number to have an effect.
<img class="center" src="img/session06/beds-data-wizard-skip.PNG"/>
---
# Less friendly csvs
<img class="center" src="img/session06/beds-data-wizard-date.png"/>
---
# Less friendly csvs
<img class="center" src="img/session06/beds-data-date-wizard.PNG"/>
---
# Look at the data
This is real data so there are real issues (which we'll work with)
```{r echo=FALSE, eval=TRUE}
kableExtra::kbl(head(beds_data))
```
---
# Dplyr
5 key verbs will help us gain a deeper understanding of our data sets.
Note summarise() can also be spelt summarize()
```{r}
dplyr::arrange()
dplyr::filter()
dplyr::mutate()
dplyr::group_by()
dplyr::summarise()
```
---
# Building with steps
These verbs aren't used independently of each other. Each can be a step in the code, like a recipe for mashed potato:
.blue[Starts with an...]
</br> potato then
</br> peel then
</br> slice into medium sized pieces then
</br> boil for 25 minutes then
</br> mash
---
# Building with steps
These verbs aren't used independently of each other. Each can be a step in the code, like a recipe for mashed potato:
.blue[Start with an R object]
</br> **potato** then
</br> peel then
</br> slice into medium sized pieces then
</br> boil for 25 minutes then
</br> mash
---
# Building with steps
These verbs aren't used independently of each other. Each can be a step in the code, like a recipe for mashed potato:
.blue[Start with an R object]
</br> **potato** then
</br> **peel()** then
</br> slice into medium sized pieces then
</br> boil for 25 minutes then
</br> mash
---
# Building with steps
These verbs aren't used independently of each other. Each can be a step in the code, like a recipe for mashed potato:
.blue[Start with an R object]
</br> **potato** then
</br> **peel()** then
</br> **slice(size = "medium")** then
</br> boil for 25 minutes then
</br> mash
---
# Building with steps
These verbs aren't used independently of each other. Each can be a step in the code, like a recipe for mashed potato:
.blue[Start with an R object]
</br> **potato** then
</br> **peel()** then
</br> **slice(size = "medium")** then
</br> **boil(time = 25)** then
</br> .blue[output = mashed potato]
---
# Building with steps
.grey[These verbs aren't used independently of each other. Each can be a step in the code, like a recipe for mashed potato:]
.blue[input object]
</br> **potato** %>%
</br> **peel()** %>%
</br> **slice(size = "medium")** %>%
</br> **boil(time = 25)**
.blue[output = mashed potato]
---
# Tidyverse syntax
.blue[input object]
data_frame .blue[then]
</br>.green[do_this(]rules.green[)] .blue[then]
</br>.green[do_this(]rules.green[)]
.blue[output = new data frame]
---
# Tidyverse syntax
</br>
data_frame .blue[%>%]
</br>.green[do_this(]rules.green[)] .blue[%>%]
</br>.green[do_this(]rules.green[)]
---
# Tidyverse syntax
</br> Combine simple pieces to solve complex puzzles
data_frame .blue[%>%]
</br>.green[do_this(]rules.green[)] .blue[%>%]
</br>.green[do_this(]rules.green[)]
---
class: inverse, middle, center
#Using dplyr
---
class: inverse, center, middle
# Q1. Which organisation provided the highest number of Mental Health (MH) beds?
---
.blue[# 1. arrange]
Reorder rows based on select variable
</br>
<img class="center" src="img/session06/arrange-verb-code.PNG" width="40%"/>
```{r arrange}
beds_data %>%
arrange(beds_av)
```
--
</br> Shortcut for %>% = <kbd>Ctrl + Shift + m</kbd>
---
.blue[# 1. arrange]
Reorder rows based on select variable...
defaults to ascending order
```{r ref.label="arrange", echo=TRUE, eval=TRUE}
```
---
.blue[# 1. arrange]
We need descending order:
```{r eval=TRUE}
beds_data %>%
arrange(desc(beds_av)) #<<
```
</br> desc() works for text and numeric variables
---
class: inverse, center, middle
# Q2. Which 2 organisations provided the highest number of MH beds in September 2018?
---
class: center, middle
# .darkgrey[Q2. Which 2 organisations provided the .blue[highest number] of MH beds in September 2018?]
.pull-left[
We'll use arrange() as before]
---
class: center, middle
# .darkgrey[Q2. Which 2 organisations provided the .blue[highest number] of MH beds .blue[in September 2018?]]
.pull-left[
.darkgrey[We'll use arrange() as before]
</br>
</br> But we require only observations with this date
]
---
.blue[# 2. filter]
pick observations by their value
<img class="center" src="img/session06/filter-verb-code.PNG" width="40%"/>
--
## == is a test of equality
```{r}
beds_data %>%
filter(date == "2018-09-01") #<<
```
The expression inside brackets should return TRUE or FALSE.
We are choosing rows where this expression is TRUE.
To exclude and test where the expression is NOT equal `!=`
```{r}
beds_data %>%
filter(date != "2018-09-01") #<<
```
---
.blue[# 2. filter]
pick observations by their value
```{r}
beds_data %>%
arrange(desc(beds_av)) %>%
filter(date == "2018-09-01") #<<
```
---
class: inverse, center, middle
# Q3. Which 5 organisations had the highest percentage bed occupancy in September 2018?
---
class: center, middle
# .darkgrey[Q3. Which 5 organisations had the .blue[highest] percentage bed occupancy in September 2018?]
We'll use arrange() as before
---
class: center, middle
# .darkgrey[Q3. Which 5 organisations had the .blue[highest] percentage bed occupancy in .blue[September 2018?]]
.darkgrey[We'll use arrange() as before]
</br> We'll use filter() as before
---
class: center, middle
# .darkgrey[Q3. Which 5 organisations had the highest .blue[percentage bed occupancy] in September 2018?]
.darkgrey[We'll use arrange() as before]
</br> .darkgrey[We'll use filter() as before]
</br> We don't have this variable...
--
but we can create it
---
.blue[# 3. mutate]
create .green[new variables] from .green[existing ones]
```{r}
beds_data %>%
mutate(perc_occ = occ_av / beds_av) #<<
```
</br> perc_occ is a new named column from existing occ_av and beds_av columns
--
## = is NOT a test of equality
---
.blue[# 3. mutate]
create .green[new variables] from .green[existing ones]
```{r}
beds_data %>%
mutate(perc_occ = occ_av / beds_av) %>% #<<
filter(date == "2018-09-01") %>%
arrange(desc(perc_occ)) #<<
```
We can refer to variables we've just created above
---
class: inverse, center, middle
# Q4. What was the mean number of beds, (across all trusts) for each value of date?
---
class: center, middle
# .darkgrey[Q4. What was the .blue[mean number of beds], (across all trusts) for each value of date?]
Let's first look at how we'd produce summary statistics like a mean...
---
.blue[# 4. summarise]
collapse many values into a single summary value
```{r summarise}
beds_data %>%
summarise(means_beds = mean(beds_av)) #<<
```
</br> Similar in syntax to mutate: means_beds is the new column name
</br> mean() function uses the existing column beds_av
--
The result is NA
```{r ref.label="summarise", eval=TRUE, echo=FALSE}
```
---
.blue[# 4. summarise]
collapse many values into a single summary value
```{r summarise-mean}
beds_data %>%
summarise(means_beds = mean(beds_av,
na.rm = TRUE)) #<<
```
</br> We'll need to remove NA values to get a suitable mean. TRUE can also be T
---
.blue[# 4. summarise]
collapse many values into a single summary value
```{r ref.label="summarise-mean", eval=TRUE}
```
This code produces a single summary value for the whole dataset
---
class: inverse, middle, center
# Q4. What was the mean number of beds (across all trusts) for each value of date?
---
class: middle, center
#.darkgrey[Q4. What was the .blue[mean number of beds] (across all trusts) for each value of date?]
.blue[Now we know how to use summarise...]
---
class: middle, center
#.darkgrey[Q4. What was the mean number of beds (across all trusts) .blue[for each value of date?]]
.darkgrey[Now we know how to use summarise...]
</br> .blue[We'll produce a summary value for **each value of date**]
---
.blue[# 5. group_by]
For each group...
```{r group-by}
beds_data %>%
group_by(date) %>% #<<
summarise(mean_beds = mean(beds_av,
na.rm = TRUE))
```
For each value of date...
</br> something must follow a group_by() as it does nothing to the output alone.
The change occurs behind the scenes.
---
.blue[# 5. group_by]
For each group... .darkgrey[summarise() produces a single summary value]
```{r ref.label="group-by", echo=TRUE, eval=TRUE}
```
---
.blue[# 5a. ungroup]
Often it's safest to remove the grouping after you've performed the required operation
<img class="center" src="img/session06/group_by_ungroup.png" width="40%"/>
```{r}
beds_data %>%
group_by(date) %>%
summarise(mean_beds = mean(beds_av, na.rm = TRUE)) %>%
ungroup()
```
---
class: inverse, middle, center
# Q5. Which 5 organisations have the highest mean % bed occupancy?
</br>
--
# (over the 5 year period)
---
class: middle, center
# .darkgrey[Q5. Which 5 organisations have the highest mean .blue[% bed occupancy]?]
.blue[Create a new variable mutate()]
---
class: middle, center
# .darkgrey[Q5. Which 5 .blue[organisations] have the highest mean % bed occupancy?]
.darkgrey[Create a new variable mutate()] </br>
</br> .blue[Then, for each of the organisations group_by()]
---
class: middle, center
# .darkgrey[Q5. Which 5 organisations have the highest .blue[mean] % bed occupancy?]
.darkgrey[Create a new variable mutate() </br>
</br> Then, for each of the organisations group_by() </br>
</br> .blue[Summary statistic using summarise()]]
---
class: middle, center
# .darkgrey[Q5. Which 5 organisations have the .blue[highest] mean % bed occupancy?]
.darkgrey[Create a new variable mutate() </br>
</br> Then, for each of the organisations group_by() </br>
</br> Summary statistic using summarise() </br>
</br> .blue[Order to find highest by using arrange()]]
---
class: middle, center
# .darkgrey[Q5. Which 5 organisations have the .blue[highest] mean % bed occupancy?]
.darkgrey[Create a new variable mutate() </br>
</br> Then, for each of the organisations group_by() </br>
</br> Summary statistic using summarise() </br>
</br> Order to find highest by using arrange()] </br>
.pull-left[
.blue[Tip: Run the code after each
new line to check it returns
the output you'd expect.]
]
---
class: inverse, middle, center
# Over to you...
---
class: middle, center
# Q5. Which 5 organisations have the highest mean % bed occupancy?
Create a new variable mutate() </br>
</br> Then, for each of the organisations group_by() </br>
</br> Summary statistic using summarise() </br>
</br> Order to find highest by using arrange() </br>
.pull-left[
.blue[Tip: Run the code after each
new line to check it returns
the output you'd expect.]
]
.pull-right[
Hint:
```{r}
beds_data %>%
mutate() %>%
group_by() %>%
summarise() %>%
arrange()
```
]
---
# Solution
```{r, eval=TRUE}
beds_data %>%
mutate(perc_occ = occ_av/beds_av) %>%
group_by(org_name) %>%
summarise(mean_pocc = mean(perc_occ, na.rm = TRUE)) %>%
arrange(desc(mean_pocc))
```
---
# Extension
How many distinct organisation names are counted under the same organisation code?
```{r eval=TRUE}
beds_data %>%
mutate(perc_occ = occ_av/beds_av) %>%
group_by(org_name) %>%
summarise(mean_pocc = mean(perc_occ, na.rm = TRUE),
# Number of data points/rows by group
number = n()) %>% #<<
arrange(desc(mean_pocc))
```
---
# Extension
How many columns associated with each observation?
Adds another summary column.
```{r eval=TRUE}
beds_data %>%
group_by(org_code) %>%
summarise(# distinct number of org_name
distinct_number = n_distinct(org_name)) %>% #<<
filter(distinct_number > 1) %>%
arrange(desc(distinct_number))
```
---
.blue[# 6. select]
select a subset of variables .darkgrey[from a existing data set]
```{r}
beds_data %>%
select(org_code,
org_name)
```
---
.blue[# 6. select]
select a subset of variables .darkgrey[from a existing data set]
```{r}
beds_data %>%
select(-org_code)
```
.green[To remove a column]
---
.blue[# 6. select]
select a subset of variables .darkgrey[from a existing data set]
```{r}
beds_data %>%
select(1:3)
```
.green[You can also refer to columns by number, here 1:3 saves having to type 1, 2, 3]
---
.blue[# 6. select]
select a subset of variables .darkgrey[from a existing data set]
```{r}
beds_data %>%
select(org_name,
everything())
```
.green[org_name appears first, followed by everything else - and isn't repeated]
---
# Not dplyr...
... but works within dplyr
[Vectors](https://datascienceplus.com/vectors-and-functions-in-r/) are the simplest type of data structure in R. Simply put, a vector is a sequence of data elements of the same basic type.
--
You can create a vector with function: c() for concatenate/combine
```{r}
c(100, 80, 200)
c("beds", "staff", "patients")
c("beds", 80, "patients") # Mixing strings (characters) and numeric values results in all being strings
```
---
# Very useful in these circumstances
```{r}
c("Bradford District Care", "Bradford District Care Trust")
```
</br> Filter by org_name IN the lookup list.
```{r }
beds_data %>%
filter(org_name %in% c("Bradford District Care", "Bradford District Care Trust")) #<<
```
</br> Filter by org_name NOT IN the lookup list.
```{r }
beds_data %>%
filter(!org_name %in% c("Bradford District Care", "Bradford District Care Trust")) #<<
```
---
# For SQL users
Code would look like this in SQL
```{sql }
SELECT *
FROM Table
WHERE Colm IN ('Bradford District Care', 'Bradford District Care Trust')
```
And
```{sql}
SELECT *
FROM Table
WHERE Colm NOT IN ('Bradford District Care', 'Bradford District Care Trust')
```
---
#### This work is licensed as
</br> Creative Commons
</br> Attribution
</br> ShareAlike 4.0
</br> International
</br> To view a copy of this license, visit
</br> https://creativecommons.org/licenses/by/4.0/