forked from HimesGroup/BMIN503_Final_Project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
final_project_LESCANO.qmd
1367 lines (1040 loc) · 61.4 KB
/
final_project_LESCANO.qmd
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
---
title: "PURPOSe: Predicting Utilization of Resources in Psychiatry Outpatient Services"
subtitle: "BMIN503/EPID600 Final Project"
author: "Nicolas Lescano"
editor: visual
format:
html:
css: "style.css"
self-contained: true
embed-resources: true
toc: true
toc-depth: 5
toc-location: left
code-fold: true
code-fold-default: true
code-tools: true
execute:
message: false
warning: false
---
[![](images/banner.png){fig-alt="banner"}](https://ibi.med.upenn.edu/)
------------------------------------------------------------------------
## Overview {#sec-overview}
This project leverages a decade of data from the Outpatient Psychiatry Clinic (OPC) of the Penn Medicine Department of Psychiatry to develop predictive models aimed at optimizing resource utilization. The goal is to address operational inefficiencies in scheduling and care allocation, ultimately enhancing patient outcomes, clinic efficiency, and provider satisfaction. Integrating principles from psychiatry, healthcare operations, and data science, the project aims to offer actionable insights into improving outpatient mental health care delivery.
Key insights were gathered from Dr. Theodore Satterthwaite (Director of Penn Lifespan Informatics and Neuroimaging Center), who provided guidance on refining the project scope and advanced predictive analytics, and Rucha Kelkar (Epic Cogito Technical Services for Penn Medicine), who offered expertise on Epic Analytics features and potential Epic Cognitive Developer Platform custom model integration.
The complete project repository, including scripts and datasets, is available [here](https://github.com/lescanico/BMIN503_Final_Project).
## Introduction {#sec-introduction}
### Challenges in Outpatient Psychiatry
Outpatient psychiatric services face unique challenges in managing the balance between provider availability and patient demand. These challenges are exacerbated by the inherent unpredictability of patient attendance and the varying degrees of care required. Inefficient scheduling can lead to prolonged wait times, rushed appointments, and increased stress for both patients and providers, thereby impacting the quality of care delivered. Additionally, the mismatch between the type of care provided and the specific needs of patients can result in suboptimal treatment outcomes and reduced overall clinic efficiency.
### Need for Advanced Analytical Approaches
The traditional appointment systems in psychiatric outpatient clinics often rely on static scheduling rules that do not account for the dynamic nature of mental health conditions and treatment responses. This project recognizes the potential of leveraging historical data and machine learning to create a more adaptive scheduling system. By predicting patient demand and resource needs more accurately, the clinic can not only improve patient care but also enhance operational efficiency, ultimately fostering a more supportive environment for both patients and staff.
![Current OPC Operational Flow](images/flow.png){fig-alt="PBH OPC Operational Flow"}
### Objectives
The final goal of this project is to integrate predictive analytics into the scheduling and resource allocation processes of outpatient psychiatric services. The aim is to develop a model that can forecast patient demand and determine optimal resource distribution. This will enable clinics to tailor their staffing and scheduling strategies in real time, thereby minimizing wait times, reducing provider workload imbalances, and ensuring that patients receive timely and appropriate care.
## Methods {#sec-methods}
### Data Sourcing & Anonymization
Data for this project was sourced from Epic Analytics, covering OPC visits from October 1, 2014, to September 30, 2024. These raw data files were initially in .xlsx format but were converted to .csv for easier manipulation and were stored securely. In the process of anonymization, medical record numbers (MRNs) were replaced with unique anonymized identifiers to ensure privacy. Additionally, sensitive demographic information such as exact birth dates and full postal codes was generalized to broader categories to maintain patient confidentiality. This step was critical for complying with data privacy regulations and ethical standards in handling patient data.
```{r anonymization, eval=FALSE}
# Load required libraries
library(readr)
library(dplyr)
library(lubridate)
# Import raw data
patient_data_raw <- read_csv("H:/secure/patient_data.csv")
visit_data_raw <- read_csv("H:/secure/visit_data.csv")
# Generate unique patient IDs for anonymization
mrn_mapping <- tibble(
MRN = unique(patient_data_raw$MRN),
patient_id = sprintf("%05d", seq_along(unique(patient_data_raw$MRN)))
)
# Save MRN mapping for potential reversibility
mrn_mapping |> saveRDS("H:/secure/mrn_mapping.rds")
# Define anonymization function
anonymize <- function(data, mapping) {
data |>
left_join(mapping, by = "MRN") |>
mutate(
year_of_birth = if ("Birth Date (UTC)" %in% names(data)) {
`Birth Date (UTC)` |> mdy() |> year()
} else NA,
postal_code = if ("Postal Code" %in% names(data)) {
`Postal Code` |> substr(1, 3)
} else NA
) |>
select(-MRN, -`Birth Date (UTC)`, -`Postal Code`)
}
# Ensure output directory exists
"datasets/" |> dir.create(showWarnings = FALSE, recursive = TRUE)
# Apply anonymization and save
patient_data_anonymized <- patient_data_raw |> anonymize(mrn_mapping)
visit_data_anonymized <- visit_data_raw |> anonymize(mrn_mapping)
patient_data_anonymized |> saveRDS("datasets/patient_data_anonymized.rds")
visit_data_anonymized |> saveRDS("datasets/visit_data_anonymized.rds")
```
### Data Preprocessing
#### Standarization
Columns across the datasets were renamed to ensure uniformity and clarity. Special characters, spaces, and all capitalizations were removed, and units and special symbols were also stripped from column names. This enhanced the dataset’s usability and ensured compatibility for downstream analysis by establishing a consistent naming convention.
Each variable was then classified according to its appropriate data type. This classification was crucial for ensuring accurate data manipulation and integrity in subsequent processing steps. Variables were categorized into types such as numeric, factor, logical, or date, based on their content and relevance to the analysis.
Once classified, the data underwent conversion where variables were transformed into their designated types. This step was essential for preparing the data for analytical modeling, ensuring all variables were in the correct format to accurately reflect their intended use in predictive models.
The final step involved creating a mapping of variable types. This mapping served as a documentation tool, providing a clear overview of each variable's original and converted data types. It was essential for traceability and debugging, allowing for a clear understanding of how data transformations impacted the analysis.
##### Renaming
```{r renaming, eval=FALSE}
# Load required libraries
library(readr)
library(dplyr)
library(stringr)
# Load anonymized data
patient_data <- readRDS("datasets/patient_data_anonymized.rds")
visit_data <- readRDS("datasets/visit_data_anonymized.rds")
# Function to standardize column names
standardize_column_names <- function(dataset) {
dataset |>
rename_with(~ . |>
str_replace_all(" \\(mmHg\\)| \\(kg/m\\^2\\)", "") |>
str_to_lower() |>
str_replace_all("[\\s\\.\\/\\?\\-\\(\\)\\%\\$]+", "_") |>
str_replace_all("_+", "_") |>
str_replace_all("_$", ""))
}
# Function to create column name mapping
create_name_mapping <- function(original_dataset, standardized_dataset) {
tibble(
Original = colnames(original_dataset),
Standardized = colnames(standardized_dataset)
)
}
# Remove columns created automatically by Epic export process
removed_columns <- c('Start Date', 'End Date')
patient_data <- patient_data |> select(-any_of(removed_columns))
visit_data <- visit_data |> select(-any_of(removed_columns))
# Standardize column names
patient_data_renamed <- patient_data |> standardize_column_names()
visit_data_renamed <- visit_data |> standardize_column_names()
# Add suffixes to common columns, excluding "patient_id"
common_cols <- colnames(patient_data_renamed) |>
intersect(colnames(visit_data_renamed)) |>
setdiff("patient_id")
patient_data_renamed <- patient_data_renamed |>
rename_with(~ paste0(., "_from_patient_dataset"), .cols = common_cols)
visit_data_renamed <- visit_data_renamed |>
rename_with(~ paste0(., "_from_visit_dataset"), .cols = common_cols)
# Create column name mappings
patient_name_mapping <- create_name_mapping(patient_data, patient_data_renamed) |>
mutate(Source = "Patient Dataset")
visit_name_mapping <- create_name_mapping(visit_data, visit_data_renamed) |>
mutate(Source = "Visit Dataset")
# Combine into a single dataframe
name_mapping <- bind_rows(patient_name_mapping, visit_name_mapping)
```
##### Retyping
###### Classification
```{r classification, eval=FALSE}
# Load required libraries
library(tibble)
library(dplyr)
library(readr)
# Manually classify variable types
variable_type_mapping <- tibble(
Variable = c(
# Identifier
"patient_id",
# Patient Dataset - Numeric
"adi_national_percentile", "adi_state_decile", "bmi_from_patient_dataset", "bp_diastolic_from_patient_dataset", "bp_systolic_from_patient_dataset", "svi_2020_socioeconomic_percentile_census_tract", "year_of_birth_from_patient_dataset", "general_risk_score",
# Patient Dataset - List as Character
"allergies_and_contraindications", "chief_complaint", "diagnosis_from_patient_dataset", "hospital_or_clinic_administered_medications", "level_of_service_from_patient_dataset" , "medical_history", "medications", "medications_ordered_from_patient_dataset", "outpatient_medications", "phq_2_total_score", "phq_9", "procedures", "procedures_ordered_from_patient_dataset", "sdoh_domains", "sdoh_risk_level",
# Patient Dataset - Factor
"country_from_patient_dataset", "country_county_from_patient_dataset", "gender_identity_from_patient_dataset", "language_from_patient_dataset", "legal_sex_from_patient_dataset", "marital_status", "patient_ethnic_group_from_patient_dataset", "patient_race_from_patient_dataset", "religion_from_patient_dataset", "rural_urban_commuting_area_primary_from_patient_dataset", "rural_urban_commuting_area_secondary_from_patient_dataset", "sex_assigned_at_birth_from_patient_dataset", "sexual_orientation_from_patient_dataset", "state_from_patient_dataset", "postal_code_from_patient_dataset", "mychart_status_from_patient_dataset",
# Patient Dataset - Logical
"interpreter_needed_from_patient_dataset", "university_of_pennsylvania_student_from_patient_dataset",
# Visit Dataset - Numeric
"age_at_visit_years", "appointment_length_minutes", "bmi_from_visit_dataset", "bp_diastolic_from_visit_dataset", "bp_systolic_from_visit_dataset", "continuity_of_care", "copay_collected", "copay_due", "encounter_to_close_day", "lead_time_days", "no_show_probability", "prepayment_collected", "prepayment_due", "time_physician_spent_post_charting_minutes", "time_physician_spent_pre_charting_minutes", "time_waiting_for_physician_minutes", "time_with_physician_minutes", "year_of_birth_from_visit_dataset",
# Visit Dataset - List as Character
"diagnosis_from_visit_dataset", "medications_ordered_from_visit_dataset", "procedures_ordered_from_visit_dataset",
# Visit Dataset - Factor
"appointment_status", "country_from_visit_dataset", "country_county_from_visit_dataset", "encounter_type", "gender_identity_from_visit_dataset", "language_from_visit_dataset", "legal_sex_from_visit_dataset", "level_of_service_from_visit_dataset", "patient_ethnic_group_from_visit_dataset", "patient_race_from_visit_dataset", "primary_benefit_plan", "primary_diagnosis", "primary_payer", "primary_payer_financial_class", "primary_provider_title", "primary_provider_type", "religion_from_visit_dataset", "rural_urban_commuting_area_primary_from_visit_dataset", "rural_urban_commuting_area_secondary_from_visit_dataset", "scheduling_source", "sex_assigned_at_birth_from_visit_dataset", "sexual_orientation_from_visit_dataset", "state_from_visit_dataset", "visit_type", "postal_code_from_visit_dataset", "primary_subscriber_group_number", "mychart_status_from_visit_dataset",
# Visit Dataset - Logical
"interpreter_needed_from_visit_dataset", "new_to_department_specialty", "new_to_facility", "new_to_provider", "portal_active_at_scheduling", "self_pay", "university_of_pennsylvania_student_from_visit_dataset",
# Visit Dataset - Date
"appointment_creation_date", "visit_date",
# Visit Dataset - hms
"appointment_time"
),
Type = c(
# Identifier
rep("identifier", 1),
# Patient Dataset - Numeric
rep("numeric", 8),
# Patient Dataset - List as Character
rep("list_as_character", 15),
# Patient Dataset - Factor
rep("factor", 16),
# Patient Dataset - Logical
rep("logical", 2),
# Visit Dataset - Numeric
rep("numeric", 18),
# Visit Dataset - List as Character
rep("list_as_character", 3),
# Visit Dataset - Factor
rep("factor", 27),
# Visit Dataset - Logical
rep("logical", 7),
# Visit Dataset - Date
rep("Date", 2),
# Visit Dataset - hms
rep("hms", 1)
)
)
# Group variables by type
group_summary <- variable_type_mapping |>
group_by(Type) |>
summarise(Variables = list(Variable), .groups = "drop") |>
mutate(Count = lengths(Variables)) |>
select(Type, Count, Variables)
# Save classification mapping
variable_type_mapping |> saveRDS("datasets/mappings/types.rds")
```
###### Conversion
```{r conversion, eval=FALSE}
# Load conversion function
source("scripts/helper-functions/convert-types.R")
# Apply function
patient_data_converted <- patient_data_renamed |> convert_types()
visit_data_converted <- visit_data_renamed |> convert_types()
```
> See [Function to Convert Data Types].
###### Mapping
```{r mapping, eval=FALSE}
# Load required libraries
library(tibble)
library(dplyr)
# Function to create variable type conversions table
create_type_conversions_mapping <- function(original_df, converted_df) {
# Get data types for original and converted datasets
tibble(
Variable = names(original_df),
Original = sapply(original_df, function(x) paste(class(x), collapse = ", ")),
Converted = sapply(converted_df, function(x) paste(class(x), collapse = ", "))
)
}
# Create the variable type mapping tables and combine them
type_conversions_mapping <- bind_rows(
create_type_conversions_mapping(patient_data_renamed, patient_data_converted),
create_type_conversions_mapping(visit_data_renamed, visit_data_converted)
)
# Capture as HTML table
source("scripts/helper-functions/capture-to-html.R")
capture_output_to_html(
"data_type_conversions.html",
"Data Type Conversions" = type_conversions_mapping
)
```
```{r, results='asis', echo=FALSE}
cat(readLines("outputs/data_type_conversions.html"), sep = "\n")
```
###### Standarization Tables
```{r standarization, eval=FALSE}
# Capture as HTML table
source("scripts/helper-functions/capture-to-html.R")
capture_output_to_html(
"standarization_tables.html",
"Standarization",
"Renaming Table" = name_mapping,
"Retyping Table" = type_conversions_mapping
)
```
> See [Function to Capture Output as HTML](#capture-output-as-html).
```{r, results='asis', echo=FALSE}
cat(readLines("outputs/standarization_tables.html"), sep = "\n")
```
#### Cleaning
In the cleaning process, data from the patient and visit datasets were first verified for shared unique identifiers to ensure consistency before merging. A left join operation was then performed to combine the datasets based on the patient ID, consolidating patient and visit information into a single dataset. Following merging, identical duplicate columns generated from the merge, which had redundant or overlapping data, were identified and processed. These columns were consolidated into single columns, removing redundancies to streamline the dataset.
For organization, the dataset was structured into logical groups to facilitate analysis. Columns were arranged by category, such as identifiers, demographic information, clinical details, and encounter specifics. This reorganization was aimed at improving the readability and accessibility of the dataset for subsequent analyses, ensuring that related data points were grouped together logically.
##### Missing Data Analysis
In the Missing Data Analysis phase, the dataset underwent a comprehensive evaluation to identify the extent of missing data across various fields. Visualizations were created to depict the percentage of missing data in each column, helping to categorize the degree of missingness and prioritize handling strategies. These visualizations differentiated between slight, moderate, significant, and extreme levels of missing data, providing a clear graphical representation of data completeness.
```{r plotting, eval=FALSE}
# Visualize Missing Data
source("scripts/helper-functions/plot-missing-values.R")
# Patient Data
plot_missing_values_by_type(patient_data_converted, 0, 5)
plot_missing_values_by_type(patient_data_converted, 5, 30)
plot_missing_values_by_type(patient_data_converted, 30, 50)
plot_missing_values_by_type(patient_data_converted, 50, 100)
# Visit Data
plot_missing_values_by_type(visit_data_converted, 0, 5)
plot_missing_values_by_type(visit_data_converted, 5, 30)
plot_missing_values_by_type(visit_data_converted, 30, 50)
plot_missing_values_by_type(visit_data_converted, 50, 100)
# Capture as HTML
source("scripts/helper-functions/capture-to-html.R")
capture_output_to_html(
"missing_data_plots.html",
"Missing Data Plots",
"Patient Data" = list(
"figures/plots/patient_data_converted_0-5_missing_plot.png",
"figures/plots/patient_data_converted_5-30_missing_plot.png",
"figures/plots/patient_data_converted_30-50_missing_plot.png",
"figures/plots/patient_data_converted_50-100_missing_plot.png"
),
"Visit Data" = list(
"figures/plots/visit_data_converted_0-5_missing_plot.png",
"figures/plots/visit_data_converted_5-30_missing_plot.png",
"figures/plots/visit_data_converted_30-50_missing_plot.png",
"figures/plots/visit_data_converted_50-100_missing_plot.png"
)
)
```
> See [Function to Plot Missing Values by Type](#plot-missing-values-by-type).
```{r, results='asis', echo=FALSE}
cat(readLines("outputs/missing_data_plots.html"), sep = "\n")
```
##### Missing Data Handling
For each category of missingness, suitable data handling strategies were proposed, considering the nature of the data and the percentage of missing values. Tables summarizing these strategies were generated to guide the implementation of appropriate methods for missing data imputation or exclusion, ensuring that the dataset's integrity was maintained while preparing it for further analysis.
```{r handling, eval=FALSE}
# Generate data handling tables with all options
source("scripts/helper-functions/generate-missing-handling-table.R")
patient_handling_table <- generate_data_handling_table(patient_data_converted)
visit_handling_table <- generate_data_handling_table(visit_data_converted)
# Capture as HTML
source("scripts/helper-functions/capture-to-html.R")
capture_output_to_html(
"missing_data_handling_options.html",
"Data Handling Tables",
"Patient Data" = patient_handling_table,
"Visit Data" = visit_handling_table
)
```
> See [Function to Generate Missing Data Handling Strategies](#generate-data-handling-table) and [Function to Calculate Summary Statistics](#calculate-summary-stats).
```{r, results='asis', echo=FALSE}
cat(readLines("outputs/missing_data_handling_options.html"), sep = "\n")
```
##### Merging
```{r merging, eval=FALSE}
# Load required libraries
library(dplyr)
# Verify unique patient_id values are shared
all_shared <- unique(patient_data_converted$patient_id) |>
(\(x) all(x %in% visit_data_converted$patient_id))() &&
unique(visit_data_converted$patient_id) |>
(\(x) all(x %in% patient_data_converted$patient_id))()
if (all_shared) {
# Perform the merge
data_merged <- visit_data_converted |>
left_join(patient_data_converted, by = "patient_id")
print("Merging complete.")
} else {
print("There are patient_id values that are not shared between the two datasets.")
}
# Sample some rows
set.seed(123)
sample_data_merged <- data_merged |>
slice_sample(n = 10)
```
##### Deduplication
```{r deduplication, eval=FALSE}
# Load required libraries
library(dplyr)
library(stringr)
# Function to process and rename only identical duplicate columns
process_identical_duplicates <- function(df, suffix_1 = "_from_patient_dataset", suffix_2 = "_from_visit_dataset") {
# Identify columns with specified suffixes
cols_suffix_1 <- grep(paste0(suffix_1, "$"), names(df), value = TRUE)
cols_suffix_2 <- grep(paste0(suffix_2, "$"), names(df), value = TRUE)
for (col in cols_suffix_1) {
# Find corresponding column with the second suffix
corresponding_col <- gsub(suffix_1, suffix_2, col)
# Check if the corresponding column exists
if (corresponding_col %in% cols_suffix_2) {
# Check if the columns are identical
if (identical(df[[col]], df[[corresponding_col]])) {
# Consolidate identical columns by renaming the first and removing the second
new_name <- gsub(paste0(suffix_1, "|", suffix_2), "", col)
names(df)[names(df) == col] <- new_name
df <- df %>% select(-all_of(corresponding_col))
}
}
}
# Return the deduplicated data
return(df)
}
# Apply the function to the merged dataset
data_deduplicated <- process_identical_duplicates(data_merged)
# Update and save Variable Type Mapping
source("scripts/helper-functions/update-type-mapping.R")
updated_mapping <- variable_type_mapping |> update_type_mapping(data_deduplicated)
variable_type_mapping <- updated_mapping
variable_type_mapping |> saveRDS("datasets/mappings/types.rds")
# Sample some rows
set.seed(123)
sample_data_deduplicated <- data_deduplicated |>
slice_sample(n = 10)
```
> See [Function to Update Variable Type Mapping](#update-variable-type-mapping).
##### Organization
```{r organization, eval=FALSE}
# Load required libraries
library(readr)
library(dplyr)
logical_groups <- list(
Identifiers = c("patient_id"),
Demographic_Info = c(
"year_of_birth", "age_at_visit_years", "legal_sex",
"gender_identity_from_patient_dataset", "gender_identity_from_visit_dataset",
"sex_assigned_at_birth_from_patient_dataset", "sex_assigned_at_birth_from_visit_dataset",
"sexual_orientation_from_patient_dataset", "sexual_orientation_from_visit_dataset",
"patient_race_from_patient_dataset", "patient_race_from_visit_dataset",
"patient_ethnic_group", "marital_status", "language",
"religion_from_patient_dataset", "religion_from_visit_dataset"
),
Sociogeographic_Info = c(
"country", "state",
"country_county_from_patient_dataset", "country_county_from_visit_dataset",
"postal_code_from_patient_dataset", "postal_code_from_visit_dataset",
"rural_urban_commuting_area_primary", "rural_urban_commuting_area_secondary",
"svi_2020_socioeconomic_percentile_census_tract", "adi_national_percentile", "adi_state_decile"
),
Clinical_Info = c(
"primary_diagnosis", "diagnosis_from_patient_dataset", "diagnosis_from_visit_dataset",
"medical_history", "allergies_and_contraindications"
),
Treatment_Info = c(
"procedures", "procedures_ordered_from_patient_dataset", "procedures_ordered_from_visit_dataset",
"medications", "hospital_or_clinic_administered_medications", "outpatient_medications",
"medications_ordered_from_patient_dataset", "medications_ordered_from_visit_dataset"
),
Health_Metrics = c(
"bmi_from_patient_dataset", "bmi_from_visit_dataset",
"bp_systolic_from_patient_dataset", "bp_systolic_from_visit_dataset",
"bp_diastolic_from_patient_dataset", "bp_diastolic_from_visit_dataset",
"phq_2_total_score", "phq_9", "general_risk_score", "sdoh_risk_level", "sdoh_domains"
),
Encounter_Info = c(
"visit_date", "visit_type", "continuity_of_care", "encounter_type",
"chief_complaint", "interpreter_needed", "appointment_status",
"appointment_creation_date", "appointment_time", "appointment_length_minutes",
"lead_time_days", "encounter_to_close_day", "scheduling_source", "no_show_probability"
),
Provider_Info = c(
"primary_provider_type", "primary_provider_title",
"time_physician_spent_pre_charting_minutes", "time_physician_spent_post_charting_minutes",
"time_with_physician_minutes", "time_waiting_for_physician_minutes"
),
Financial_Info = c(
"primary_benefit_plan", "primary_payer", "primary_payer_financial_class", "self_pay",
"copay_due", "copay_collected", "prepayment_due", "prepayment_collected",
"primary_subscriber_group_number", "level_of_service_from_patient_dataset",
"level_of_service_from_visit_dataset"
),
Status_Info = c(
"portal_active_at_scheduling", "mychart_status",
"new_to_department_specialty", "new_to_facility", "new_to_provider",
"university_of_pennsylvania_student"
)
)
# Reorganize data
data_organized <- data_deduplicated |>
select(all_of(unlist(logical_groups, use.names = FALSE))) |>
arrange(patient_id, visit_date)
# Sample some rows
set.seed(123)
sample_data_organized <- data_organized |>
slice_sample(n = 10)
```
##### Cleaning Samples
```{r cleaning_samples, eval=FALSE}
# Capture as HTML tables
source("scripts/helper-functions/capture-to-html.R")
capture_output_to_html(
"cleaning_samples.html",
"Samples",
"Merged Data" = sample_data_merged,
"Deduplicated Data" = sample_data_deduplicated,
"Organized Data" = sample_data_organized
)
```
```{r, results='asis', echo=FALSE}
cat(readLines("outputs/cleaning_samples.html"), sep = "\n")
```
#### Preparation
During the aggregation, various functions were utilized to normalize data encoding, compute modes for specific variables like 'sdoh_risk_level', and convert complex data entries into more straightforward numeric representations. The dataset underwent encoding normalization to ensure uniform character encoding across all text fields. A custom function was implemented to calculate the mode for 'sdoh_risk_level' to handle categorical data effectively. Furthermore, strings of numbers separated by new lines were processed to compute their mean values, consolidating the data further.
For the encoding process, all factor variables within the dataset were encoded into integers to facilitate computational efficiency and preparedness for analytical procedures. This step involved storing a mapping of the original factor levels to their new encoded forms, ensuring that no information was lost and that the transformations could be reversed or interpreted in future analyses.
Additionally, the type mapping was updated to reflect changes in data structure and types post-aggregation and encoding. This involved adjusting the classifications of certain variables to better suit their role in the subsequent analysis, ensuring data integrity and appropriateness for the modeling steps that follow.
Reassessment of missing data was performed after these transformations to ensure that the data handling strategies were still appropriate given the new data structure. This included visualizing missing data by type and reassessing the handling strategies to adapt to the encoded and aggregated data's needs.
> **Note**: Following the aggregation process, the resulting datasets are substantially reduced in size. Therefore, they can now be saved and reloaded between code chunks to enable independent execution.
##### Aggregation
```{r aggregation, eval=FALSE}
# Load required libraries
library(data.table)
library(stringr)
library(dplyr)
# Function to normalize encoding
normalize_encoding <- function(df) {
df[] <- lapply(df, function(col) {
if (is.character(col)) {
iconv(col, from = "", to = "UTF-8", sub = "byte") # Replace invalid characters
} else {
col
}
})
df
}
# Custom function to compute mode for 'sdoh_risk_level'
compute_mode <- function(x) {
x <- x[x != "Unknown"]
if (length(x) == 0) return(NA_character_)
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
# Function to convert strings of numbers separated by "\r\n" to means
mean_from_string <- function(x) {
sapply(strsplit(x, "\\r?\\n", perl = TRUE), function(vals) {
vals_num <- suppressWarnings(as.numeric(vals))
if (all(is.na(vals_num))) NA_real_ else mean(vals_num, na.rm = TRUE)
})
}
# Convert to data.table for faster processing
data_aggregated <- copy(data_organized)
setDT(data_aggregated)
# Normalize encoding for character columns
data_aggregated <- normalize_encoding(data_aggregated)
# Select columns to aggregate by count
cols_to_aggregate <- setdiff(
names(data_aggregated)[sapply(data_aggregated, is.character)],
c("patient_id", "phq_2_total_score", "phq_9", "sdoh_risk_level")
)
# Aggregate by count
for (col in cols_to_aggregate) {
data_aggregated[[col]] <- ifelse(
is.na(data_aggregated[[col]]),
NA_real_,
vapply(strsplit(data_aggregated[[col]], "\\r?\\n", perl = TRUE),
function(x) length(unique(x)),
numeric(1))
)
}
# Aggregate 'phq_2_total_score' and 'phq_9' by mean
data_aggregated[, phq_2_total_score := mean_from_string(phq_2_total_score)]
data_aggregated[, phq_9 := mean_from_string(phq_9)]
# Aggregate 'sdoh_risk_level' by mode
data_aggregated[, sdoh_risk_level := {
splits <- strsplit(sdoh_risk_level, "\\r?\\n", perl = TRUE)
sapply(splits, compute_mode)
}]
# Inspect sdoh_risk_level unique values
unique(data_aggregated$sdoh_risk_level)
# Consolidate 'Low Risk ' (extra space) with 'Low Risk'
data_aggregated <- data_aggregated |>
mutate(sdoh_risk_level = str_replace_all(sdoh_risk_level, fixed("Low Risk "), "Low Risk"))
# Convert 'sdoh_risk_level' to factor
data_aggregated$sdoh_risk_level <- as.factor(data_aggregated$sdoh_risk_level)
# Save aggregated data
data_aggregated |> saveRDS("datasets/processed/data_aggregated.rds")
```
##### Encoding
```{r encoding, eval=FALSE}
# Load required libraries
library(readr)
library(dplyr)
# Load Aggregated Data
data_aggregated <- readRDS("datasets/processed/data_aggregated.rds")
# Initialize a list to store encoding mapping
mapping_list <- list()
# Encode all factor variables in the dataset
for (col in colnames(data_aggregated)) {
if (is.factor(data_aggregated[[col]])) {
# Store the mapping
mapping_list[[col]] <- data.frame(
Variable = col,
Encoded = seq_along(levels(data_aggregated[[col]])),
Value = levels(data_aggregated[[col]])
)
# Replace the factor variable with its integer encoding
data_aggregated[[col]] <- as.integer(data_aggregated[[col]])
}
}
# Reconvert to factors
data_aggregated <- data_aggregated %>%
mutate(across(where(is.integer), as.factor))
# Save mapping and encoded dataset
mapping_list |> saveRDS("datasets/mappings/encoding.rds")
data_aggregated |> saveRDS("datasets/processed/data_encoded.rds")
print("Encoding complete. Mapping and encoded dataset saved.")
```
```{r retyping, eval=FALSE}
# Load required libraries
library(readr)
library(dplyr)
# Load type mapping
types <- readRDS("datasets/mappings/types.rds")
# Update type mapping
retypes <- types |>
mutate(Type = case_when(
Variable == "sdoh_risk_level" ~ "factor",
Type == "list_as_character" ~ "numeric",
TRUE ~ Type
))
retypes |> saveRDS("datasets/mappings/retypes.rds")
print("Retyped mapping saved.")
```
##### Missing Data Analysis Reassessment
```{r replotting, eval=FALSE}
# Load required libraries
library(readr)
# Load encoded dataset and retyped mapping
data_encoded <- readRDS("datasets/processed/data_encoded.rds")
variable_type_mapping <- readRDS("datasets/mappings/retypes.rds")
# Visualize Missing Data
source("scripts/helper-functions/plot-missing-values.R")
# Encoded Data
plot_missing_values_by_type(data_encoded, 0, 5)
plot_missing_values_by_type(data_encoded, 5, 30)
plot_missing_values_by_type(data_encoded, 30, 50)
plot_missing_values_by_type(data_encoded, 50, 100)
# Capture as HTML
source("scripts/helper-functions/capture-to-html.R")
capture_output_to_html(
"missing_data_replots.html",
"Missing Data Plots",
"Encoded Data" = list(
"figures/plots/data_encoded_0-5_missing_plot.png",
"figures/plots/data_encoded_5-30_missing_plot.png",
"figures/plots/data_encoded_30-50_missing_plot.png",
"figures/plots/data_encoded_50-100_missing_plot.png"
)
)
```
```{r, results='asis', echo=FALSE}
cat(readLines("outputs/missing_data_replots.html"), sep = "\n")
```
##### Missing Data Handling Reassessment
```{r rehandling, eval=FALSE}
# Load required libraries
library(readr)
# Load encoded dataset and retyped mapping
data_encoded <- readRDS("datasets/processed/data_encoded.rds")
variable_type_mapping <- readRDS("datasets/mappings/retypes.rds")
# Generate data handling tables with all options
source("scripts/helper-functions/generate-missing-handling-table.R")
encoded_data_handling_table <- generate_data_handling_table(data_encoded)
# Capture as HTML
source("scripts/helper-functions/capture-to-html.R")
capture_output_to_html(
"encoded_data_handling_options.html",
"Data Handling Table",
"Encoded Data" = encoded_data_handling_table
)
```
```{r, results='asis', echo=FALSE}
cat(readLines("outputs/encoded_data_handling_options.html"), sep = "\n")
```
##### Imputation
```{r imputation, eval=FALSE}
# Load required libraries
library(readr)
library(tidyr)
library(dplyr)
library(mice)
# Load encoded dataset
data_encoded <- readRDS("datasets/processed/data_encoded.rds")
# Calculate missingness percentage for numeric variables
missingness_info <- data_encoded |>
select(where(is.numeric)) |>
summarise(across(everything(), ~ mean(is.na(.)) * 100)) |>
pivot_longer(cols = everything(), names_to = "variable", values_to = "missing_percent")
# Categorize variables based on missingness thresholds
missingness_info <- missingness_info |>
mutate(category = case_when(
missing_percent < 5 ~ "<5%",
missing_percent >= 5 & missing_percent < 30 ~ "5-30%",
missing_percent >= 30 & missing_percent < 50 ~ "30-50%",
missing_percent >= 50 ~ ">50%"
))
# Impute data based on categories
data_imputed <- data_encoded
# Loop through categories and apply appropriate imputation
for (cat in unique(missingness_info$category)) {
vars_in_category <- missingness_info |>
filter(category == cat) |>
pull(variable)
# Skip if no variables fall into the current category
if (length(vars_in_category) == 0) next
if (cat == "<5%") {
# Impute with mean
data_imputed[vars_in_category] <- data_imputed[vars_in_category] |>
mutate(across(everything(), ~ ifelse(is.na(.), mean(., na.rm = TRUE), .)))
} else if (cat == "5-30%") {
# Impute with median
data_imputed[vars_in_category] <- data_imputed[vars_in_category] |>
mutate(across(everything(), ~ ifelse(is.na(.), median(., na.rm = TRUE), .)))
} else if (cat == "30-50%") {
# Use MICE for imputation
# Subset the data for variables in this category
mice_data <- data_imputed[vars_in_category]
# Check if MICE can run
if (all(sapply(mice_data, function(x) all(is.na(x))))) {
warning(paste("Skipping MICE for category:", cat, "- no non-NA data available."))
next
}
# Run MICE
mice_imputed <- mice(mice_data, m = 1, method = 'pmm', maxit = 5, seed = 123)
# Extract the completed dataset
imputed_subset <- complete(mice_imputed)
# Replace in the main dataset
data_imputed[vars_in_category] <- imputed_subset
} else if (cat == ">50%") {
# Handle separately - may decide to drop these columns
message(paste("Dropping variables with >50% missingness:", paste(vars_in_category, collapse = ", ")))
data_imputed <- data_imputed |> select(-all_of(vars_in_category))
}
}
# Save the imputed dataset
data_imputed |> saveRDS("datasets/processed/data_imputed.rds")
# Print completion message
message("Imputation completed and dataset saved to 'datasets/processed/data_imputed.rds'")
```
##### Preparation Samples
```{r preparation_samples, eval=FALSE}
# Load required libraries
library(readr)
library(dplyr)
# Load preparation datasets
data_aggregated <- readRDS("datasets/processed/data_aggregated.rds")
data_encoded <- readRDS("datasets/processed/data_encoded.rds")
data_imputed <- readRDS("datasets/processed/data_imputed.rds")
set.seed(123)
sample_data_aggregated <- data_aggregated |>
slice_sample(n = 10)
sample_data_encoded <- data_encoded |>
slice_sample(n = 10)
sample_data_imputed <- data_imputed |>
slice_sample(n = 10)
# Capture Data Samples
source("scripts/helper-functions/capture-to-html.R")
capture_output_to_html(
"preparation_samples.html",
"Samples",
"Aggregated Data" = sample_data_aggregated,
"Encoded Data" = sample_data_encoded,
"Imputed Data" = sample_data_imputed
)
```
```{r, results='asis', echo=FALSE}
cat(readLines("outputs/preparation_samples.html"), sep = "\n")
```
#### Feature Engineering
The following basic features were obtained:
- **Visit Count**: The total number of visits each patient made.
- **First Visit**: The date of the first visit within the dataset's timeframe.
- **Last Visit**: The date of the last visit within the dataset's timeframe.
- **Visit Span Years**: The total number of years between the first and last visit, calculated as a continuous variable.
- **Near Start Boundary**: A boolean indicator showing whether the first visit occurred within the first six months of the study period (6 months is the standard OPC timeframe to define "loss to follow up").
- **Near End Boundary**: A boolean indicator showing whether the last visit occurred within the last six months of the study period.
- **Boundary Flag**: A boolean indicator that is true if either the first or last visit is near the study period boundaries.
- **Adjusted Span Years**: The number of years between the first and last visit, adjusted for boundary effects.
- **Visits Per Year**: The average number of visits per year, adjusted for any boundary effects.
```{r feature_engineering, eval=FALSE}
# Load required libraries
library(dplyr)
library(tidyr)
library(lubridate)
# Load datasets
data_encoded <- readRDS("datasets/processed/data_encoded.rds")
encoding <- readRDS("datasets/mappings/encoding.rds")
# Define dataset boundaries
dataset_start <- as.Date("2014-10-01")
dataset_end <- as.Date("2024-09-30")
# Select provider types
selected_providers <- c("Physician", "Psychiatrist", "Resident", "Nurse Practitioner")
# Decode
selected_provider_codes <- encoding$primary_provider_type |>
filter(Value %in% selected_providers) |>
pull(Encoded)
# Filter `data_encoded` by provider_type
data_filtered <- data_encoded |>
filter(primary_provider_type %in% relevant_provider_codes)
# Feature Extraction: Summarize by patient_id
data_featured <- data_filtered |>
group_by(patient_id) |>
summarise(
visit_count = n(),
first_visit = min(visit_date, na.rm = TRUE),
last_visit = max(visit_date, na.rm = TRUE),
visit_date_min = min(visit_date, na.rm = TRUE),
visit_date_max = max(visit_date, na.rm = TRUE)
) |>
ungroup()
# Filter patients with more than 2 visits
data_featured <- data_featured |>
filter(visit_count > 2)
# Feature Engineering: Boundary Handling and Adjusted Metrics
data_featured <- data_featured |>
mutate(
visit_span_years = as.numeric(difftime(last_visit, first_visit, units = "days")) / 365.25,
near_start_boundary = first_visit <= (dataset_start + months(6)), # Within 6 months of start
near_end_boundary = last_visit >= (dataset_end - months(6)), # Within 6 months of end