-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEpiR_handbook2.R
2470 lines (1591 loc) · 74 KB
/
EpiR_handbook2.R
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
# =========== Epidemiology R Handbook
library(dplyr)
pacman::p_load(
rio, # importing data, handles various file types
here, # relative file pathways
janitor, # data cleaning and tables
lubridate, # working with dates
epikit, # age_categories() function
tidyverse # data management and visualization
)
# import data
# linelist_raw <- import("linelist_raw.xlsx")
head(linelist_raw)
# review data
# skim = skimr::skim(linelist_raw)
# column names
names(linelist_raw)
# =========================== Cleaning Pipeline
# automatic column name cleaning === janitor package
# pipe the raw dataset through the function clean_names(), assign result as "linelist"
df.clean <- linelist_raw %>%
janitor::clean_names()
# see the new column names
names(df.clean)
# === manually rename() columns
# can also use the select() method for same result
df.clean.2 = df.clean %>%
janitor::clean_names() %>%
# new_name = old_name
rename(date_infection = infection_date,
date_hospitalization = hosp_date)
# Excel data has merged cells => problems, use this:
# df_raw <- openxlsx::readWorkbook("linelist_raw.xlsx", fillMergedCells = TRUE)
# duplicated column names => errors, manually fix them
# --- select column you want
selected_columns = df.clean.2 %>%
select(case_id, date_onset, date_hospitalization, fever)
selected_columns
# ---- organize columns order with ''everything()''
# name the columns you want to have priority then everything() afterwards
df.clean.2 %>%
select( date_onset, date_hospitalization, everything()) %>%
names()
# --- select columns based on class using where()
# get columns with numeric class
df.clean.3 %>% select(
where(is.numeric)) %>%
names()
# --- get columns with "date" in them
df.clean.2 %>%
select(contains("date")) %>%
names()
# -- remove columns
df.clean.3 = df.clean.2 %>%
select( c(-row_num, -merged_header, -x28))
# --- remove duplicates
df.clean.3 = df.clean.3 %>% distinct()
# --- mutate a new column
df.clean.3 = df.clean.3 %>%
mutate( BMI = wt_kg / (ht_cm/100)^2)
# --- data type class
class(df.clean.3$age) # char
# mutate the class to numeric
df.clean.3 = df.clean.3 %>%
mutate(age = as.numeric(age))
# ----- NORMALIZE data using mutate
# normalize age to mean for all rows
df.clean.3 = df.clean.3 %>%
mutate(age.norm = age / mean(age, na.rm=T))
# normalize hospital group ages
df.clean.3 = df.clean.3 %>%
group_by(hospital) %>%
mutate(age.hosp.norm = age / mean(age, na.rm=T))
# --- apply transformations all at once to columns using across()
# --- change values manually you can use the recode() function within the mutate() function.
#
# fix incorrect values # old value # new value
# df <- df %>%
# mutate(date_onset = recode(date_onset, "2014-14-15" = "2014-04-15"))
# --- replace()
# mutate(col_to_change = replace(col_to_change, criteria for rows, new value))
df.clean.3 = df.clean.3 %>%
mutate(gender = replace(gender, case_id == "2195", "Transgender"))
# --- replace NAs use replace_na()
df.clean.3 = df.clean.3 %>%
mutate(hospital = replace_na(hospital, "Missing"))
# -- faster method is use forcats function: fct_explicit_na()
df.clean.2 %>%
mutate(hospital = fct_explicit_na(hospital))
# -- review age_years column distribution
hist(df.clean.3$age)
summary(df.clean.3$age, na.rm=T)
# --- age categories with break points for factor
# base R : use cut() to do same thing
library(epikit)
df.clean.3 = df.clean.3 %>%
mutate(age_cat = age_categories(age,
breakers = c(0,5,10,15,20,30,
40,50,60,70,80,90)))
# show table
table(df.clean.3$age_cat, useNA = "always")
# ---- age quantiles
quantile(df.clean.3$age,
probs = c(0,.25,.5,.75,.9,.95), # percentiles
na.rm = T)
# -- edit Hospital name
df.clean.3 = df.clean.3 %>%
mutate(hospital = recode(hospital,
"Central Hopital" = "Port Hospital"))
# -- quantiles/ deciles --------------- code gives errors
# df.clean.3 = df.clean.3 %>%
# mutate(deciles = cut(age,
# breaks= quantile(age,
# probs= seq(0,1, by=0.1),
# na.rm=T))) %>%
# janitor::tabyl(deciles)
# ----------- filter for condition
gender.f = df.clean.3 %>%
filter(gender == "f") %>%
drop_na(case_id, age )
# --- hist date onset with 50 breaks
hist(df.clean.3$lon, breaks = 50)
# -- design a filter
table(Hospital = df.clean.3$hospital,
YearOnset = lubridate::year(df.clean.3$date_onset),
useNA = "always")
# --- exclude criteria
# rows with onset in 2012 and 2013 at either hospital A, B, or Port:
nrow(df.clean.3 %>%
filter(hospital %in% c("Hospital A",
"Hospital B") | date_onset < as.Date("2013-06-01")))
# rows from Hospitals A & B with missing onset dates
nrow(df.clean.3 %>%
filter(hospital %in% c('Hospital A', 'Hospital B') & is.na(date_onset)))
df.clean.3 = df.clean.3 %>%
filter(date_onset > as.Date("2013-06-01") | (is.na(date_onset) & !hospital
%in% c("Hospital A", "Hospital B")))
nrow(df.clean.3)
table(Hospital = df.clean.3$hospital, # hospital name
YearOnset = lubridate::year(df.clean.3$date_onset), # year of date_onset
useNA = "always")
# ======== end of cleaning pipeline ==================
# ================= working with dates
pacman::p_load(
lubridate, # general package for handling and converting dates
# linelist, # has function to "guess" messy dates
aweek, # another option for converting dates to weeks, and weeks to dates
zoo, # additional date/time functions
tidyverse, # data management and visualization
rio)
# pacman::p_install_gh("appliedepi/epirhandbook")
# pacman::p_load(epirhandbook)
# download only the linelist example data into a folder on your computer
# get_data(file = "linelist_cleaned.rds")
ebola <- import("linelist_cleaned.xlsx")
# get system date
Sys.Date()
# get system time
Sys.time()
# ------------- convert df dates to date class
ebola = ebola %>%
mutate(date_onset = as.Date(date_onset, format= "%d/%m/%Y"),
date_hospitalisation = as.Date(date_hospitalisation, format= "%d/%m/%Y"),
date_outcome = as.Date(date_outcome, format= "%d/%m/%Y"),
date_infection = as.Date(date_infection, format= "%d/%m/%Y"))
# lubridate :: floor_date() unit="week" week_start= 1 (Monday)
# weekly counts
weekly_counts = ebola %>%
drop_na(date_onset) %>%
mutate(weekly_cases = floor_date(
date_onset,
unit = "week"
)) %>%
count(weekly_cases) %>% # group data by week and count rows per group (creates column 'n')
tidyr::complete( # ensure all weeks are present, even those with no cases reported
weekly_cases = seq.Date(
from = min(weekly_cases),
to = max(weekly_cases),
by= "week"
),
fill = list(n=0) # fill NA in the n counts with 0
)
# lubridate also has functions week(), epiweek(), and isoweek(),
# each of which has slightly different start dates and other nuances
library(aweek)
library(lubridate)
# -- deal with different timezones to standardize datetimes
time_now <- Sys.time()
time_now
# use with_tz() to assign a new timezone to the column, while CHANGING the clock time
time_london_now <- with_tz(time_now, "Europe/London")
# use force_tz() to assign a new timezone to the column, while KEEPING the clock time
time_london_local <- force_tz(time_now, "Europe/London")
t.delta = time_london_now - time_london_local
t.delta
# ====== lag() and lead() functions for case counts per week calculations
# counts = ebola %>%
# mutate(cases_prev_wk = lag(cases_wk, n = 1),
# case_diff = cases_wk - cases_prev_wk)
# ============================ strings & char
library(stringr)
str_c("String1", "String2", "String3")
str_c("String1", "String2", "String3", sep = ", ")
first_names <- c("abdul", "fahruk", "janice")
last_names <- c("hussein", "akinleye", "okeke")
str_c(first_names, last_names, sep = " ", collapse = "; ")
cat(str_c(first_names, last_names, sep = " ", collapse = ";\n"))
str_glue("Data include {nrow(ebola)} cases and are
current to {format(Sys.Date(), '%d %b %Y')}.")
str_glue("ebola as of {current_date}.\nLast case hospitalized on {last_hospital}.\n{n_missing_onset} cases are missing date of onset and not shown",
current_date = format(Sys.Date(), '%b %d %Y'),
last_hospital = format(as.Date(max(ebola$date_hospitalisation, na.rm=T)), '%b %d %Y'),
n_missing_onset = nrow(ebola %>% filter(is.na(ebola$date_onset)))
)
# == new df
case_table = data.frame(
# columns = << rows >>
zone = c("Zone 1", "Zone 2", "Zone 3", "Zone 4", "Zone 5"),
new_cases = c(3, 7, 1, 0, 15),
total_cases = c(40,4,25,10,103)
)
# Use str_glue_data(), which is specially made for taking data from data frame rows:
case_table %>%
str_glue_data("{zone}: {new_cases} ({total_cases} total cases)")
# or have on 1-line
str_c(case_table$zone, case_table$new_cases, sep = " = ", collapse = "; ")
library(tidyr)
library(tidyverse)
# combine columns into a df
symptoms.df <- data.frame(
case_ID = c(1:6),
symptoms = c("jaundice, fever, chills", # patient 1
"chills, aches, pains", # patient 2
"fever", # patient 3
"vomiting, diarrhoea", # patient 4
"bleeding from gums, fever", # patient 5
"rapid pulse, headache"), # patient 6
outcome = c("Recover", "Death", "Death", "Recover", "Recover", "Recover"))
df_split <- separate(df, symptoms, into = c("sym_1", "sym_2", "sym_3"), extra = "merge")
str_split(string = "jaundice, fever, chills",
pattern = ",")
symptoms <- c("jaundice, fever, chills", # patient 1
"chills, aches, pains", # patient 2
"fever", # patient 3
"vomiting, diarrhoea", # patient 4
"bleeding from gums, fever", # patient 5
"rapid pulse, headache") # patient 6
str_split(symptoms, ",")
# --arrange by alphabet
# strings
health_zones <- c("Alba", "Takota", "Delta")
# return the alphabetical order
str_order(health_zones)
# - truncate
original <- "Symptom onset on 4/3/2020 with vomiting"
str_trunc(original, 10, "center")
stringy = " whitespace "
str_trim(stringy )
str_squish(stringy)
# search terms
occupation_med_frontline <- str_c("medical", "medicine", "hcw", "healthcare", "home care", "home health",
"surgeon", "doctor", "doc", "physician", "surgery", "peds", "pediatrician",
"intensivist", "cardiologist", "coroner", "nurse", "nursing", "rn", "lpn",
"cna", "pa", "physician assistant", "mental health",
"emergency department technician", "resp therapist", "respiratory",
"phlebotomist", "pharmacy", "pharmacist", "hospital", "snf", "rehabilitation",
"rehab", "activity", "elderly", "subacute", "sub acute",
"clinic", "post acute", "therapist", "extended care",
"dental", "dential", "dentist", sep = "|")
occupation_med_frontline
sum(str_detect(string = occupation_med_frontline, pattern = "subacute"))
sum(str_detect(string = occupation_med_frontline, pattern = "nurse|nursing|rn"))
str_extract_all(occupation_med_frontline, pattern = "medical|medicine")
# -- replace
outcome <- c("Karl: dead",
"Samantha: dead",
"Marco: not dead")
str_replace_all(string = outcome, pattern = "dead", replacement = "deceased")
# ==================================== regex
# Character set Matches for
# "[A-Z]" any single capital letter
# "[a-z]" any single lowercase letter
# "[0-9]" any digit
# [:alnum:] any alphanumeric character
# [:digit:] any numeric digit
# [:alpha:] any letter (upper or lowercase)
# [:upper:] any uppercase letter
# [:lower:] any lowercase letter
# Meta character Represents
# "\\s" a single space
# "\\w" any single alphanumeric character (A-Z, a-z, or 0-9)
# "\\d" any single numeric digit (0-9)
test <- "A-AA-AAA-AAAA"
str_extract_all(test, "A{2}")
str_extract_all(test, "A{2,4}")
str_extract_all(test, "A+") # groups 1+
pt_note <- "Patient arrived at Broward Hospital emergency ward at 18:00 on 6/12/2005. Patient presented with radiating abdominal pain from LR quadrant. Patient skin was pale, cool, and clammy. Patient temperature was 99.8 degrees farinheit. Patient pulse rate was 100 bpm and thready. Respiratory rate was 29 per minute."
str_extract_all(pt_note, "[A-Za-z]+")
# expression "[0-9]{1,2}" matches to consecutive numbers that are 1 or 2 digits in length.
# It could also be written "\\d{1,2}", or "[:digit:]{1,2}"
str_extract_all(pt_note, "[0-9]{1,2}")
# ===================== FACTORS
# convert a column from character or numeric class to a factor if you want to
# set an intrinsic order to the values (“levels”) so they can be displayed
# non-alphabetically in plots and tables. Another common use of factors is
# to standardise the legends of plots so they do not fluctuate if certain
# values are temporarily absent from the data.
#
library(forcats)
pacman::p_load(
lubridate, # general package for handling and converting dates
# linelist, # has function to "guess" messy dates
aweek, # another option for converting dates to weeks, and weeks to dates
zoo, # additional date/time functions
tidyverse, # data management and visualization
rio)
ebola <- import("linelist_cleaned.xlsx")
# --- change to datetimes
ebola = ebola %>%
mutate(date_hospitalisation = as.Date(date_hospitalisation, format= "%m/%d/%Y"),
date_onset = as.Date(date_onset, format="%m/%d/%Y" ),
date_outcome = as.Date(date_outcome, format = "%m/%d/%Y" ),
date_infection = as.Date(date_infection, format = "%m/%d/%Y" )
)
ebola <- ebola %>%
mutate(delay_cat = case_when(
# criteria # new value if TRUE
days_onset_hosp < 2 ~ "<2 days",
days_onset_hosp >= 2 & days_onset_hosp < 5 ~ "2-5 days",
days_onset_hosp >= 5 ~ ">5 days",
is.na(days_onset_hosp) ~ NA_character_,
TRUE ~ "Check me"))
# new column delay_cat is a categorical column of class Character - not yet a factor.
# Thus, in a frequency table, we see that the unique values appear
# in a default alpha-numeric order - an order that does not make much intuitive sense:
# table uses the cross-classifying factors to build a contingency table
# of the counts at each combination of factor levels.
table(ebola$delay_cat, useNA = "always")
ggplot(data= ebola) +
geom_bar(mapping = aes(x= delay_cat))
# --- convert to a factor, from chr
ebola = ebola %>%
mutate(delay_cat = fct_relevel(delay_cat,"<2 days", "2-5 days", ">5 days"))
# unique “values” in this column are now considered “levels” of the factor.
# The levels have an order, which can be printed with the base R function levels(),
# or alternatively viewed in a count table via table() from base R or tabyl() from janitor.
levels(ebola$delay_cat)
ggplot(data = ebola) +
geom_bar(mapping = aes(x= delay_cat))
# -- add/drop levels
ebola %>%
mutate(delay_cat = fct_expand(delay_cat, "Not admitted","Patient Transferred")) %>%
tabyl(delay_cat)
# -- drop NAs
ebola %>%
mutate(delay_cat = fct_drop(delay_cat)) %>%
tabyl(delay_cat)
# --- factor gender column
ebola = ebola %>%
mutate(gender = as.factor(gender))
# ordered by frequency
ggplot(data = ebola, aes(x = fct_infreq(delay_cat)))+
geom_bar()+
labs(x = "Delay onset to admission (days)",
title = "Ordered by frequency")
# reversed frequency
ggplot(data = ebola, aes(x = fct_rev(fct_infreq(delay_cat))))+
geom_bar()+
labs(x = "Delay onset to admission (days)",
title = "Reverse of order by frequency")
# boxplots ordered by original factor levels
ggplot(data = ebola)+
geom_boxplot(
aes(x = delay_cat,
y = ct_blood,
fill = delay_cat))+
labs(x = "Delay onset to admission (days)",
title = "Ordered by original alpha-numeric levels")+
theme_classic()+
theme(legend.position = "none")
# boxplots ordered by median CT value
ggplot(data = ebola)+
geom_boxplot(
aes(x = fct_reorder(delay_cat, ct_blood, "median"),
y = ct_blood,
fill = delay_cat))+
labs(x = "Delay onset to admission (days)",
title = "Ordered by median CT blood value in group")+
theme_classic()+
theme(legend.position = "none")
epidemic_data <- ebola %>% # begin with the ebola
filter(date_onset < as.Date("2014-09-21")) %>% # cut-off date, for visual clarity
count( # get case counts per week and by hospital
epiweek = lubridate::floor_date(date_onset, "week"),
hospital
)
ggplot(data = epidemic_data)+ # start plot
geom_line( # make lines
aes(
x = epiweek, # x-axis epiweek
y = n, # height is number of cases per week
color = fct_reorder2(hospital, epiweek, n)))+ # data grouped and colored by hospital, with factor order by height at end of plot
labs(title = "Factor levels (and legend display) by line height at end of plot",
color = "Hospital") # change legend title
ebola %>%
mutate(gender = fct_recode(
gender,
'Female' = "f",
"Male" = "m"
)) %>%
# replace_na(gender, "Transgender") %>%
tabyl(gender)
ebola %>%
mutate(hospital = fct_other(
hospital,
keep = c("Port Hospital","Central Hospital"),
other_level = "Other Hospital"
)) %>%
tabyl(hospital)
ebola %>%
mutate(hospital = fct_lump(
hospital,
n=2, # keep top 2 levels
other_level = "Other Hospital"
)) %>%
tabyl(hospital)
ggplot(data = ebola)+
geom_bar(mapping = aes(x = hospital, fill = age_cat)) +
scale_fill_discrete(drop = FALSE)+ # show all age groups in the legend, even those not present
labs(
title = "All age groups will appear in legend, even if not present in data")
ebola %>%
mutate(epiweek_date = floor_date(date_onset, "week")) %>% # create week column
ggplot()+ # begin ggplot
geom_histogram(mapping = aes(x = epiweek_date))+ # histogram of date of onset
scale_x_date(date_labels = "%Y-W%W") # adjust display of dates to be YYYY-WWw
# ============ PIVOT !
# pivot tables, which are tables of statistics that summarise the data of a more extensive table
# conversion of a table from long to wide format, or vice versa.
library(tidyverse)
library(rio)
library(here)
ebola <- import("linelist_cleaned.xlsx")
count_data <- import("malaria_facility_count_data.rds")
count_data$data_date %>% min()
count_data$data_date %>% max()
# basic initial look at data
ggplot(count_data) +
geom_col(aes(x = data_date, y = malaria_tot), width = 1)
#------------- pivot longer()
# It accepts a range of columns to transform (specified to cols = ).
# Therefore, it can operate on only a part of a dataset.
# This is useful for the malaria data, as we only want to pivot the case count columns.
df_long <- count_data %>%
pivot_longer(
cols = c(`malaria_rdt_0-4`, `malaria_rdt_5-14`, `malaria_rdt_15`, `malaria_tot`)
)
df_long
# the df now has 4x's the rows
# provide column with a tidy select helper function
df_long = count_data %>%
pivot_longer(
cols = starts_with("malaria_"),
names_to = "age_group",
values_to = "counts"
)
df_long
# We can now pass this new dataset to ggplot2, and map the new column count to the
# y-axis and new column age_group to the fill = argument (the column internal color).
# This will display the malaria counts in a stacked bar chart, by age group:
ggplot(data = df_long) +
geom_col(
mapping = aes(x = data_date, y = counts, fill = age_group),
width = 1
)
# ! we have also included the total counts from the malaria_tot column,
# so the magnitude of each bar in the plot is twice as high as it should be.
df_long %>%
filter(age_group != "malaria_tot") %>% # filter out the total column
ggplot() +
geom_col(
aes(x = data_date, y = counts, fill = age_group),
width = 1
)
# ---- pivoting data of different class types
# you will encounter will be the need to pivot columns that contain different classes of data.
# This pivot will result in storing these different data types in a single column, which is not a good situation.
# There are various approaches one can take to separate out the mess this creates
# In order to work with these data, we need to transform the data frame to long format,
# but keeping the separation between a date column and a character (status) column, for each observation for each item.
# Example columns: id | obs1_date | obs1_status ... < very wide dataset >
# df %>%
# pivot_longer(
# cols = -id,
# names_to = c("observation",".value"),
# names_sep = "_"
# )
# df_long <-
# df_long %>%
# mutate(
# date = date %>% lubridate::as_date(), # convert dates into date class
# observation =
# observation %>%
# str_remove_all("obs") %>% # remove the obs from obs1
# as.numeric() # convert char to numeric
# )
# ------- long to wide table, pivot_wider()
# A typical use-case is when we want to transform the results of an analysis
# into a format which is more digestible for the reader (such as a Table for presentation).
# Suppose that we want to know the counts of individuals in the different age groups, by gender:
# df_wide <-
# df %>%
# count(age_cat, gender)
#
# df_wide
# a long dataset that is great for producing visualizations in ggplot2, but not ideal for presentation in a table:
# ggplot(df_wide) +
# geom_col(aes(x = age_cat, y = n, fill = gender))
# argument names_from specifies the column from which to generate the new column names,
# while the argument values_from specifies the column from which to take the values to populate the cells.
# The argument id_cols = is optional, but can be provided a vector of column names that should not be pivoted,
# and will thus identify each row.
# table_wide <-
# df_wide %>%
# pivot_wider(
# id_cols = age_cat,
# names_from = gender,
# values_from = n
# )
# table_wide %>%
# janitor::adorn_totals(c("row", "col")) %>% # adds row and column totals
# knitr::kable() %>%
# kableExtra::row_spec(row = 10, bold = TRUE) %>%
# kableExtra::column_spec(column = 5, bold = TRUE)
# ======= fill a dataset
df1 <-
tibble::tribble(
~Measurement, ~Facility, ~Cases,
1, "Hosp 1", 66,
2, "Hosp 1", 26,
3, "Hosp 1", 8,
1, "Hosp 2", 71,
2, "Hosp 2", 62,
3, "Hosp 2", 70,
1, "Hosp 3", 47,
2, "Hosp 3", 70,
3, "Hosp 3", 38,
)
df1
# -- year column
df2 <-
tibble::tribble(
~Year, ~Measurement, ~Facility, ~Cases,
2000, 1, "Hosp 4", 82,
2001, 2, "Hosp 4", 87,
2002, 3, "Hosp 4", 46
)
df2
# -- join tables with bind_rows()
df_combined <-
bind_rows(df1, df2) %>%
arrange(Measurement, Facility)
df_combined
# === fill()
df_combined %>%
fill(Year, .direction = "up") # "down"
# --
df_combined <-
df_combined %>%
arrange(Measurement, desc(Facility))
df_combined <-
df_combined %>%
fill(Year, .direction = "down")
df_combined
ggplot(df_combined) +
aes(Year, Cases, fill = Facility) +
geom_col()
# --- end of pivoting data
# ------------------ grouping data for descriptive stats
library(tidyverse)
ebola <- import("linelist_cleaned.xlsx")
# -- group_by()
# group df column outcome
df.outcome = ebola %>%
group_by(outcome)
df.outcome
# Note that there is no perceptible change to the dataset after running group_by(),
# until another dplyr verb such as mutate(), summarise(), or arrange() is applied on the “grouped” data frame.
# --- unique groups
# To see the groups and the number of rows in each group,
# pass the grouped data to tally().
# To see just the unique groups without counts you can pass to group_keys().
# based on outcome column groups, get the number of rows for death
nrow(ebola %>% filter(outcome =="Death"))
nrow(ebola %>% filter(outcome =="Recover"))
nrow(ebola %>% filter(is.na(outcome))) # how many NAs in group outcome
# You can group by more than one column. Below, the data frame is grouped by outcome and gender, and then tallied
ebola %>%
group_by(outcome, gender) %>%
tally()
# --- add new columns within a group_by() like a mutate()
ebola %>%
group_by(
age_class = ifelse(age >= 18, "adult", "child")) %>%
tally(sort= T)
# -- add/drop grouping columns
# group_by() on data that are already grouped, the old groups will be removed and the new one(s) will apply.
# If you want to add new groups to the existing ones, include the argument .add = TRUE.
# group by outcome
by_outcome = ebola %>%
group_by(outcome)
# Add grouping by gender in addition
by_outcome_gender <- by_outcome %>%
group_by(gender, .add = TRUE)
# -- ungroup()
ebola %>%
group_by(outcome, gender) %>%
tally() %>%
ungroup()
# ------------- summarize()
# summarize()) takes a data frame and converts it into a new summary data frame,
# with columns containing summary statistics that you define.
# On an ungrouped data frame, the summary statistics will be calculated from all rows.
# Applying summarise() to grouped data produces those summary statistics for each group.
# summary statistics on ungrouped linelist
ebola %>%
summarise(
n_cases = n(),
mean_age = mean(age_years, na.rm=T),
max_age = max(age_years, na.rm=T),
min_age = min(age_years, na.rm=T),
n_males = sum(gender == "m", na.rm=T))
# summary statistics on grouped linelist
ebola %>%
group_by(outcome) %>%
summarise(
n_cases = n(),
mean_age = mean(age_years, na.rm=T),
max_age = max(age_years, na.rm=T),
min_age = min(age_years, na.rm=T),
n_females = sum(gender == "f", na.rm=T))
# ---- tally()
# summarise(n = n()), and does not group data. Thus, to achieve grouped tally it must follow a group_by()
ebola %>%
group_by(outcome) %>%
tally(sort = TRUE)
# ---- count()
ebola %>% count(outcome)
ebola %>%
count(age_class = ifelse(age >= 18, "adult", "child"), sort = T)
# to summarise the number of hospitals present for each gender
ebola %>%
# produce counts by unique outcome-gender groups
count(gender, hospital) %>%
# gather rows by gender (3) and count number of hospitals per gender (6)
count(gender, name = "hospitals per gender" )
ebola %>%
as_tibble() %>% # convert to tibble for nicer printing
add_count(hospital) %>% # add column n with counts by hospital
select(hospital, n, everything()) # re-arrange for demo purposes
# -- add totals
library(janitor)
ebola %>% # df ebola
tabyl(age_cat, gender) %>% # cross-tabulate counts of two columns
adorn_totals(where = "row") %>% # add a total row
adorn_percentages(denominator = "col") %>% # convert to proportions with column denominator
adorn_pct_formatting() %>% # convert proportions to percents
adorn_ns(position = "front") %>% # display as: "count (percent)"
adorn_title( # adjust titles
row_name = "Age Category",
col_name = "Gender")
# --- group by date
# When grouping data by date, you must have (or create) a column for the date unit of interest - for example “day”, “epiweek”, “month”, etc
# “fill-in” any dates in the sequence that are not present in the data.