forked from annalhead/CPRD_multimorbidity_trends
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Datacleaning_neat.R
2640 lines (2149 loc) · 86 KB
/
Datacleaning_neat.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
# Data cleaning
#This file is for downloading and cleaning the data required for estimating
# multimorbidity incidence and prevalence by IMD quintile.
#Our patient sample was derived from May 2020 Aurum database
#Inputs:
#1. Aurum lookup files (July 2020)
#2. 1,00,140 patients from May 2020 Aurum database; using: patient, practice,
# observation, & linked IMD files
#3. Codelists derived from CALIBER lists (available here:
# https://github.com/annalhead/CPRD_multimorbidity_codelists)
#######################################################################
#### SET UP ####
#######################################################################
library(data.table)
#library(foreign)
#library(stringr)
#library(ggplot2)
library(fst) #for quick writing of files
data.table::setDTthreads(10) #this is so that don't use all the processors
# Shortcuts for the directories
data_dir_CPRD <-
function(x = character(0))
paste0("/mnt/", Sys.info()[["user"]],
"/UoL/CPRD2019mm/Data May 2020/", x)
data_dir_lookup <-
function(x = character(0))
paste0("/mnt/", Sys.info()[["user"]],
"/UoL/CPRD2019mm/Dictionaries etc/", x)
data_dir_DL <-
function(x = character(0))
paste0("/mnt/", Sys.info()[["user"]],
"/UoL/CPRD2019mm/Disease_lists/", x)
#Chris' package for data management
library(Rcpp)
sourceCpp(data_dir_lookup("shift_bypid.cpp"),
cacheDir = "/mnt/alhead/.cache")
shift_bypid <- #for quick shifting of cols by id
function(x, lag, id, replace = NA) {
if (typeof(x) == "integer") {
return(shift_bypidInt(x, lag, replace, id))
} else if (typeof(x) == "logical") {
return(shift_bypidBool(x, lag, replace, id))
} else if (typeof(x) == "double") {
return(shift_bypidNum(x, lag, replace, id))
} else
stop("class of x not supported")
}
#######################################################################
#### LOAD LOOKUP FILES - AURUM DOCUMENTATION ####
#######################################################################
# Aurum dictionary
aurumdict <-
fread(
file = data_dir_lookup("202007_EMISMedicalDictionary.txt"),
header = TRUE,
sep = "\t" ,
colClasses = 'character'
) #reads everything in as characters
setnames(aurumdict, tolower(names(aurumdict))) #making all col names lower case
# Patient type
patienttype <- fread(
file = data_dir_lookup("PatientType.txt"),
header = TRUE,
sep = "\t" ,
colClasses = 'character'
)
# Unit type for numerical values
numunit <- fread(
file = data_dir_lookup("NumUnit.txt"),
header = TRUE,
sep = "\t" ,
colClasses = 'character'
)
# Observation type
obstype <- fread(
file = data_dir_lookup("ObsType.txt"),
header = TRUE,
sep = "\t",
colClasses = 'character'
)
#######################################################################
#### LOAD MEDCODEIDS FOR CONDITIONS OF INTEREST ####
#######################################################################
# Loading the list of conditions of interest (incl disease system and gives
# number to each disease) & the codelists
#read in the summary list of diseases of interest
diseasesum <- fread(data_dir_DL("DiseaseSumm.csv"))
fullcodelistmedid <-
read_fst(data_dir_DL("fullcodelistmedidJAN2021.fst"),
as.data.table = TRUE)
fullcodelistmedid[, disease_num := as.numeric(disease_num)]
codelistsinglemedid <-
read_fst(data_dir_DL("codelistsinglemedidJAN2021.fst"),
as.data.table = TRUE)
codelistsinglemedid[, disease_num := as.numeric(disease_num)]
codelistmultimedid <-
read_fst(data_dir_DL("codelistmultimedidJAN2021.fst"),
as.data.table = TRUE)
codelistmultimedid[, disease_num := as.numeric(disease_num)]
# Medcodeids for test value results
testcodes <- fread(
file = data_dir_DL("testcodes.csv"),
header = TRUE,
sep = ",",
colClasses = 'character'
)
#######################################################################
#### LOAD PRACTICE FILES ####
#pracid: Practice identifier
#region: Region - Value to indicate where in the UK the practice is based.
#The region denotes the Strategic Health Authority for practices within England,
#and the country i.e. Wales, Scotland, or Northern Ireland for the rest
#lcd: Last Collection Date - Date of the last collection for the practice
#uts: Up To Standard Date - Date at which the practice data is deemed to be of
#research quality.
#Derived using a CPRD algorithm that primarily looks at practice death
#recording and gaps in the data
#######################################################################
if (file.exists(data_dir_CPRD("practice.fst"))) {
practice <-
read_fst(data_dir_CPRD("practice.fst"), as.data.table = TRUE)
} else {
require(tidyverse)
require(data.table)
#Puts together a list of all the files matching the pattern
pracfiles <-
list.files(
data_dir_CPRD("Patient_Practice_Staff_Referral"),
pattern = ".*Practice_001.txt[.]zip",
recur = T,
full = T
)
practice <- data.table()
for (fn in pracfiles[1:2]) {
subtab <-
readr::read_tsv(fn, col_type = cols(.default = col_character())) %>%
as.data.table() %>%
mutate(pracid = as.numeric(pracid)) %>%
mutate(lcd = as.IDate(lcd, format = "%d/%m/%Y"))
practice <- rbind(practice, subtab)
rm(subtab)
}
rm(fn)
#Checking for missing values
practice[is.na(region),] # prac 20957 has no region.
#dropping uts col as empty - not yet available in Aurum
practice[, uts := NULL]
#only need 1 record per practice (there are 2 because 2 extractions)
setkey(practice, pracid, lcd)
practice <-
practice[practice[, .I[1], by = c("pracid", "lcd")]$V1]
write_fst(practice, data_dir_CPRD("practice.fst"), 100)
}
#######################################################################
#### LOAD PATIENT & IMD FILES, COMBINE WITH PRACID INFO ####
# & ADD IN BLACK ETHNICITY (FOR CKD) FROM OBSERVATION FILES
#patid: Patient Identifier. Last 3 digits are practice identifiers
#pracid: practice id
#gender: 1 = male (recode to "M"), 2 = female ("F" ), 3 = indeterminate ("I")
#NB: in practice this is sex
#yob: Birth Year
#regstartdate: The date that the patient registered with
#the CPRD contributing practice.
#Most recent date the patient is recorded as having registered at the practice.
#If a patient deregistered for a period of time and returned,
#the return date would be recorded.
#patienttypeid: The category that the patient has been assigned
#to e.g. private, regular, temporary. Lookup: PatientType.txt.
#emis_ddate: Date of death as recorded in the EMIS software. Researchers are
#advised to treat the emis_ddate with caution and consider using the
#cprd_ddate variable below.
#regenddate: Date the patient's registration at the practice ended.
#This may represent a transfer-out date or death date.
#Transferred out period is the time between a patient transferring out and
#re-registering at the same practice. 0 is continuous registration.
#cprd_ddate: Estimated date of death of patient- derived using a CPRD algorithm
#######################################################################
if (file.exists(data_dir_CPRD("patient.fst"))) {
#patient <- read_fst(data_dir_CPRD("patient.fst"), as.data.table = TRUE)
patient <- read_fst(
data_dir_CPRD("patient.fst"),
columns = c(
"patid",
"gender",
"imd",
"black",
"yob" ,
"dob",
"reg1yr",
"censordate",
"censorreason",
"region"
),
as.data.table = TRUE
)
} else {
require(tidyverse)
require(data.table)
#Puts together a list of all the files matching the pattern
patfiles <-
list.files(
data_dir_CPRD("Patient_Practice_Staff_Referral"),
pattern = ".*Patient_001.txt[.]zip",
recur = T,
full = T
)
patient <- data.table()
for (fn in patfiles[1:2]) {
subtab <-
readr::read_tsv(fn, col_type = cols(.default = col_character())) %>%
as.data.table()
subtab[, `:=` (
pracid = as.numeric(pracid),
yob = as.numeric(yob),
#correcting date formats:
emis_ddate = as.IDate(emis_ddate, format = "%d/%m/%Y"),
regstartdate = as.IDate(regstartdate, format = "%d/%m/%Y"),
regenddate = as.IDate(regenddate, format = "%d/%m/%Y"),
cprd_ddate = as.IDate(cprd_ddate, format = "%d/%m/%Y"),
gender = factor(
gender,
levels = c("1", "2", "3"),
labels = c("M", "F", "I")
)
)][, c("mob", "usualgpstaffid") := NULL]
patient <- rbind(patient, subtab)
rm(subtab)
}
rm(fn, patfiles)
#patient acceptability flag & patient type
table(patient$acceptable) # everybody 'acceptable'
table(patient$patienttypeid) # everybody type 3: "regular"
#view(patienttype)
rm(patienttype)
#including only patients with
#acceptable flags and regular patienttype
patient <- patient[acceptable == 1 & patienttypeid == 3,]
acceptpatno <- patient[, length(patid)] #total no. participants
#Looking at gender
patient[, .(.N, "%" = .N / acceptpatno), by = gender] #tablulating gender
#Removing cols no longer need
#Creating 3 new variables: censordate, dob, reg1yr
patient[, `:=` (
patienttypeid = NULL,
acceptable = NULL,
#creating new end date of reg: this is regenddate for those where recorded:
censordate = regenddate,
#making everybody born on the 1st July:
dob = as.IDate(paste0(yob, "0701"), format = "%Y%m%d"),
#creating variable for date that have 1 year of registration:
reg1yr = regstartdate + 365
)]
#ignoring emis deathdate as per CPRD recommendations
patient[!is.na(cprd_ddate) &
(cprd_ddate != regenddate | is.na(regenddate)),
.N] # 66,114: cprd_ddate recorded but different to regenddate
patient[cprd_ddate > regenddate,
.N] #431 cprd_ddate after regenddate
patient[cprd_ddate - regenddate > 30,
.N] #257 cprd_ddate more than 1 month after regenddate
patient[regenddate > cprd_ddate,
.N] #65,683 cprd_ddate before regenddate
patient[regenddate - cprd_ddate > 30,
.N] #11,216 cprd_ddate more than 1 month before regenddate
patient[regenddate - cprd_ddate > 365,
.N] #654 cprd_ddate more than 1 month before regenddate
#if cprd_ddate recorded and different to regenddate, using the earliest.
#Although there are some observations recorded within the time between
#cprd_ddate and regendate, these will be ignored in the analysis
patient[!is.na(cprd_ddate) &
(cprd_ddate != regenddate | is.na(regenddate)),
censordate := ifelse(cprd_ddate > regenddate, regenddate, cprd_ddate)]
#creating censor reason 1 = death, 0 = other
patient[, `:=` (censorreason = factor(ifelse(is.na(cprd_ddate), 0, 1)))]
#Adding in info from practice file
patient[practice, on = 'pracid', `:=` (region = i.region, lcd = i.lcd)]
#for people with no regenddate, changing censordate
#to the practice last collection date
patient[, `:=` (#emis_ddate = NULL, #keep this for now....
censordate = as.IDate(ifelse(is.na(censordate), lcd, censordate),
format = "%d/%m/%Y"))]
patient[, lcd := NULL] #dropping lcd as no longer needed
#adding in IMD data - 1 least deprived; 5 most deprived
IMD <- fread(
file = data_dir_CPRD(
"IMD Oct2020/Aurum_linked/patient_imd2015_19_173_request2.txt"
),
header = TRUE,
sep = "\t",
colClasses = 'character'
)
patient[IMD, on = 'patid', imd := i.imd2015_5]
table(patient$imd) #1,345 have no imd recorded
patient[, .(.N, "%" = .N / acceptpatno), keyby = imd] #tablulating imd
rm(acceptpatno, IMD)
write_fst(patient, data_dir_CPRD("patient.fst"), 100)
#Extracting codes for black ethnicity and adding to patient,
#this is for calculating egfr
black <- fread(
file = data_dir_lookup("ckdepi_black.txt"),
header = TRUE,
sep = "\t" ,
colClasses = 'character'
) #reads everything in as characters
black_mc <- black$medcodeid
require(tidyverse)
require(data.table)
#Puts together a list of all the files matching the pattern
obsfiles <- list.files(
data_dir_CPRD("Observation") ,
pattern = ".*txt[.]zip",
recur = T,
full = T
)
obstabblack <- data.table()
for (fn in obsfiles[1:111]) {
subtab <-
readr::read_tsv(fn, col_type = cols(.default = col_character())) %>%
select(patid, medcodeid) %>%
filter(medcodeid %in% black_mc) %>% as.data.table()
obstabblack <- rbind(obstabblack, subtab)
rm(subtab)
}
rm(fn)
patient[, black := ifelse(patid %in% obstabblack$patid, 1, 0)][
, black := factor(black)]
rm(obstabblack, black_mc)
write_fst(patient, data_dir_CPRD("patient.fst"), 100)
}
#Total number of patient years
patient[censordate - reg1yr >= 0, sum(censordate - reg1yr) / 365.24]
#######################################################################
#### LOAD OBSERVATION FILE DATA FOR MEDCODEIDS OF INTEREST ####
#patid: Patient identifier
#consid: Consultation identifier
#pracid: CPRD Practice identifier
#obsid: Observation identifier
#obsdate: Event date
#enterdate: Entered date
#staffid: Staff identifier
#parentobsid: Parent observation identifier. Observation identifier (obsid)
#that is the parent to the observation. This enables grouping of multiple
#observations, such as systolic and diastolic blood pressure, or
#blood test results.
#medcodeid: Medical code. CPRD unique code for the medical term selected by
#the GP. Lookup: Medical dictionary
#value: Value. Measurement or test value
#numunitid:Numeric unit identifier. Unit of measurement. Lookup: NumUnit.txt
#obstypeid: Observation type identifier. Type of observation (allergy,
#family history, observation). Lookup: ObsType.txt
#numrangelow: Numeric range low. Value representing the low boundary of the
#normal range for this measurement
#numrangehigh: Numeric range high. Value representing the high boundary of the
#normal range for this measurement
#probobsid: Problem observation identifier. Observation identifier (obsid) of
#any problem that an observation is associated with. An example of this might
#be an overarching condition that the current observation is associated with
#such as 'wheezing' with the problem observation identifier that links to an
#observation of 'asthma', that in turn contains information in the
#problem table. Link Observation table
#######################################################################
if (file.exists(data_dir_CPRD("obstaball_raw.fst"))) {
obstaball <-
read_fst(data_dir_CPRD("obstaball_raw.fst"), as.data.table = TRUE)
} else {
require(tidyverse)
require(data.table)
#Puts together a list of all the files matching the pattern
obsfiles <- list.files(
data_dir_CPRD("Observation"),
pattern = ".*txt[.]zip",
recur = T,
full = T
)
# Medcodeids of interest
obscodes <-
unique(c(fullcodelistmedid$medcodeid, testcodes$medcodeid))
obstaball <- data.table()
for (fn in obsfiles[1:111]) {
subtab <-
readr::read_tsv(fn, col_type = cols(.default = col_character())) %>%
select(
patid,
obsid,
obsdate,
enterdate,
medcodeid,
value,
numunitid,
obstypeid,
numrangelow,
numrangehigh
) %>%
filter(medcodeid %in% obscodes) %>%
as.data.table() %>%
mutate(enterdate = as.IDate(enterdate, format = "%d/%m/%Y")) %>%
mutate(obsdate = as.IDate(obsdate, format = "%d/%m/%Y"))
obstaball <- rbind(obstaball, subtab)
rm(subtab)
}
rm(fn, obscodes, obsfiles)
obstaball[, `:=` (
value = as.numeric(value),
numrangelow = as.numeric(numrangelow),
numrangehigh = as.numeric(numrangehigh)
)]
#looking at enterdate and obsdate
obstaball[is.na(obsdate), .N] #44,999 (0.01% of all obs)
obstaball[is.na(enterdate), .N] #0
obstaball[obsdate > enterdate, .N] #48,8431
head(obstaball[obsdate > enterdate,
.(obsdate, enterdate)],
100) #lots of these have enterdates before 1900
obstaball[obsdate > enterdate &
year(enterdate) > 1900,
.N] #7,771 obsdates are after sensible enterdates
obstaball[year(enterdate) > 1900 &
obsdate - enterdate > 30,
.N] #5,813 are more than a month apart
obstaball[year(enterdate) > 1900 & obsdate - enterdate > 365,
.N] #3,184 are more than a year apart
obstaball[enterdate > obsdate,
.N] #12,486,515 (27.2%) were entered after obsdate.
obstaball[enterdate - obsdate > 30,
.N] #4,286,698 (9.3%) less problematic
obstaball[enterdate - obsdate > 365,
.N] #3,166,846 (6.9%)
#Creating an eventdate variable: this is obsdate if recorded,
#otherwise enterdate unless enterdate is before 1900
obstaball[, eventdate :=
as.IDate(ifelse(
!is.na(obsdate),
obsdate,
ifelse(enterdate > "1900-01-01", enterdate, NA)
),
format = "%d/%m/%Y")]
setkey(obstaball, patid, eventdate)
#saving this is before deleting any observations
write_fst(obstaball, data_dir_CPRD("obstaball_raw_Dec13.fst"), 100)
}
#######################################################################
#### BASIC CLEANING OF OBSERVATION FILE DATA ####
#######################################################################
# Adding in basic patient info
obstaball[patient, on = 'patid', `:=` (
yob = i.yob,
censordate = i.censordate,
regenddate = i.regenddate,
cprd_ddate = i.cprd_ddate
)]
obstaball[year(eventdate) < yob, .N] #3,101obs before year of birth
obstaball[eventdate > censordate, .N] #16072 obs after censordate
obstaball[eventdate - censordate > 30, .N] #8078
obstaball[eventdate - censordate > 365, .N] # 2603
obstaball[(cprd_ddate < eventdate & eventdate < regenddate) |
(regenddate < eventdate & eventdate < cprd_ddate),
.N] #3,666 obs fall in between regenddate & cprd_ddate
#Getting rid of obs before year of birth and after censor year
obstaball <- obstaball[!is.na(eventdate) &
yob <= year(eventdate) &
censordate >= eventdate]
#Removing unwanted cols
obstaball[, c("yob", "censordate", "regenddate", "cprd_ddate") := NULL]
# Looking at obstype
#1 Allergy; 2 Annotated Image; 3 Document; 4 Family history; 5 Immunisation
#6 Investigation; 7 Observation; 8 Referral; 9 Test Request; 10 Value;
#11 Care plan
obstaball[, obstypeid := as.numeric(obstypeid)]
obstaball[, .N, keyby = obstypeid]
#obstypeid N
#1 14365
#2 1873
#3 80614
#4 2791
#5 877
#6 2633914
#7 17163358
#8 84825
#9 28456
#10 25848407
#not including "family history" records (N = 2791)
obstaball <- obstaball[obstypeid != 4,]
setkey(obstaball, patid, eventdate)
#In order to apply alogrithms, separating out into:
#single code ever recorded, multivisit criteria, test results,
#Single code ever recorded
obstabsingle <-
obstaball[medcodeid %in% codelistsinglemedid$medcodeid,]
obstabsingle <- merge(
obstabsingle,
fullcodelistmedid[, .(medcodeid, disease_num)],
by = "medcodeid",
all.x = T,
all.y = F,
allow.cartesian = TRUE
)
obstabsingle[,.N] #N = 16,626,523
#Test codes
obstabtest <-
obstaball[medcodeid %in% testcodes$medcodeid,] #N = 27,620,559
obstabtest[, .N]
obstabtest[, value := as.numeric(value)]
obstabtest[aurumdict, on = 'medcodeid', `:=`
(descr = i.term)] #adding in medcodeid descr etc
obstabtest[numunit, on = 'numunitid',
unittype := i.Description] #adding in unittype descr
#Getting rid of records recorded before yob
obstabtest[patient, on = 'patid', yob := i.yob]
obstabtest[yob + 18 > year(eventdate),
.N] #538,418 were recorded before 18
obstabtest[is.na(value) | value <= 0,
.N] #864,876 obs have value unrecorded or <=0
obstabtest <- obstabtest[yob + 18 <= year(eventdate) &
#excluding tests before 18!is.na(value) &
value > 0, ] #excluding obs with a negative value
obstabtest[, yob := NULL]
write_fst(obstabtest, data_dir_CPRD("obstabtest_14Dec.fst"), 100)
#Multi visit criteria required
obstabmulti <-
obstaball[medcodeid %in% codelistmultimedid$medcodeid,]
obstabmulti <- merge(
obstabmulti,
fullcodelistmedid[, .(medcodeid, disease_num)],
by = "medcodeid",
all.x = T,
all.y = F,
allow.cartesian = TRUE
)
obstabmulti[, .N] #N = 12,902,947
rm(obstaball)
#######################################################################
#### CLEANING OF TEST VALUE DATA - CKD ####
#######################################################################
## Adding in CKD from test results
# GFR & Creatinine test results for CKD
#A patient is defined as having had CKD stage 3 or above at a specified date:
# IF egfr_ckdepi recorded on or before specified date, THEN
#IF egfr_ckdepi <60 ml/min on the most recent date (index date)
#before the specified date
#AND
#IF egfr_ckdepi <60 ml/min on any date greater than 90 days
#BEFORE the index date above
#THEN classify as having CKD3 or above
#ELSE the patient is not defined as having CKD stage 3 or above.
#Where egfr_ckdepi up to and including 31 Dec 2013 is defined as:
# egfr_ckdepi = 141 * min(crea_gprd * 0.010746 / K, 1)^alpha
#* max(crea_gprd * 0.010746 / K, 1)^-1.209
#* 0.993^age * 1.018 [if female] * 1.159 [if black]
#where:
# alpha = -0.329 for females, -0.411 for males
#K = 0.7 for females, 0.9 for males
#Where egfr_ckdepi from and including 1 Jan 2014 is defined as:
# egfr_ckdepi = 141 * min(crea_gprd * 0.010746 / K, 1)^alpha
#* max(crea_gprd * 0.0.011312/ K, 1)^-1.209
#* 0.993^age * 1.018 [if female] * 1.159 [if black]
#where:
# alpha = -0.329 for females, -0.411 for males
#K = 0.7 for females, 0.9 for males
#Where crea_gprd is defined as:
# IF enttype = 165 [Serum creatinine]
#AND data1 [Operator] = 3 ["="] AND data2 [Value] > 0
#THEN crea_gprd = data2
#Assumes serum creatinine unit is micromol/L
#(https://www.caliberresearch.org/portal/show/crea_gprd)
#"Measurement of serum creatinine in primary care. Values of zero are discarded.
#The distribution of measurements with units recorded as mmol/L, mol/L or umol/L
#are all consistent with being recorded in micromol/L. Hence we assume the
#units are micromol/L regardless of the actual units stated."
## looking at serum creatinine. #The Kuan algorithm specifies serum creatinine
#Looking at code frequencies
#select & restrict to recorded values
creaobs <-
obstabtest[medcodeid %in% c("380389013", "259054018", "457927010")
& !is.na(value) & value > 0,]
creaobs[, .N] #4,403,816
creaobs[, .N, by = c("descr", "medcodeid")][order(-N)]
#DECIDED TO USE THESE THREE CODES:
#1: 380389013 Serum creatinine 4,400,928
#2: 259054018 Serum creatinine NOS 2,108
#3: 457927010 Corrected serum creatinine level 780
#Looking at unit frequencies
creaobs[, .N, by = unittype][order(-N)]
creaobs[, summary(value)]
#Normal ref range Adult F 45 - 84 M 59 - 104
#https://www.esht.nhs.uk/wp-content/uploads/2017/08/Clinical-Biochemistry-reference-ranges-handbook.pdf
#https://onlinelibrary-wiley-com.liverpool.idm.oclc.org/doi/epdf/10.1002/pds.2203
#this gives biological plausability limits of less than20 micromol/L (0.2 mg/dL)
#and greater than 1800 micromol/L (20 mg/dL)
#Let's stick to these.
#1800 micromol/L in other valid units would still be below 1800:
creaobs[value < 1800 ,
summary(value)]
#Regardless of units stated, the IQR is within the normal ref range
ggplot(creaobs[value < 1800], aes(x = value)) +
geom_histogram(binwidth = 1)
#outliers are 1.5*IQR either side of lower & upper quartiles - 4.23%:
ggplot(creaobs[value < 1800], aes(x = value)) +
geom_boxplot(
outlier.colour = "red",
outlier.shape = 8,
outlier.size = 4
)
micromol <- c("umol/l",
"micmol/l",
"micromol/l",
"??mol/l",
"umol//l",
"mcmol/l")
creaobs[tolower(descr) %like% "serum" &
tolower(unittype) %in% micromol, .N] #4,291,157 (97% of serum)
#looking at only those with the specified units
creaobs[value < 1800 &
tolower(unittype) %in% micromol, summary(value)]
#1800 micromol/L in other valid units would still be below 1800
#Regardless of units stated, the IQR is within the normal ref range
ggplot(creaobs[value < 1800 &
tolower(unittype) %in% micromol, ], aes(x = value)) +
geom_histogram(binwidth = 1)
#outliers are 1.5*IQR either side of lower & upper quartiles - 4.23%
ggplot(creaobs[value < 1800 &
tolower(unittype) %in% micromol, ], aes(x = value)) +
geom_boxplot(
outlier.colour = "red",
outlier.shape = 8,
outlier.size = 4
)
quantile(creaobs[tolower(unittype) %in% micromol, value],
c(0.005, .025, .25, .75, .975, .995))
#plotting only those within the 'plausible' limits
ggplot(creaobs[value < 1800 &
value > 20 & tolower(unittype) %in% micromol],
aes(x = value)) +
geom_boxplot(
outlier.colour = "red",
outlier.shape = 8,
outlier.size = 4
)
#outliers are 1.5*IQR either side of lower & upper quartiles
ggplot(creaobs[value < 1800 &
value > 20 & tolower(unittype) %in% micromol],
aes(x = value)) +
geom_histogram(binwidth = 1)
creaobs[value < 1800 &
value > 20 & tolower(unittype) %in% micromol,
.N] #4289848/4403816 - 97.4% all records with micromol units
summary(creaobs[value < 1800 &
value > 20 & tolower(unittype) %in% micromol,
value])
#looking at those with different units
#For those with different units, most still in the range above.
#If they were actually recorded in mmol/l mol/l mg/dl they wouldn't be.
#So assuming that they are
creaobs[value < 1800 &
!tolower(unittype) %in% micromol, summary(value)]
#1800 micromol/L in other valid units would still be below 1800
#Regardless of units stated, the IQR is within the normal ref range
ggplot(creaobs[value < 1800 &
!tolower(unittype) %in% micromol, ], aes(x = value)) +
geom_histogram(binwidth = 1)
ggplot(creaobs[value < 1800 &
!tolower(unittype) %in% micromol, ], aes(x = value)) +
geom_boxplot(
outlier.colour = "red",
outlier.shape = 8,
outlier.size = 4
)
#outliers are 1.5*IQR either side of lower & upper quartiles - 4.23%
#Have quite similar distributions?
quantile(creaobs[!tolower(unittype) %in% micromol, value],
c(0.005, .025, .25, .75, .975, .995)) #more in the tails
#plotting only those within the 'plausible' limits for micromol units
ggplot(creaobs[value < 1800 &
value > 20 & !tolower(unittype) %in% micromol],
aes(x = value)) +
geom_boxplot(
outlier.colour = "red",
outlier.shape = 8,
outlier.size = 4
)
#outliers are 1.5*IQR either side of lower & upper quartiles
ggplot(creaobs[value < 1800 &
value > 20 & !tolower(unittype) %in% micromol],
aes(x = value)) +
geom_histogram(binwidth = 1)
creaobs[value < 1800 &
value > 20 & !tolower(unittype) %in% micromol, .N]
#111273/112659 - 98.77% all records without micromol units
summary(creaobs[value < 1800 &
value > 20 & !tolower(unittype) %in% micromol,
value])
#same range in mmol/l is 0.02 to 1.8
creaobs[tolower(unittype) %in% "mmol/l" &
value < 1.8 & value > 0.02,
.N] #there are 65 of these
#same range in mol/l is 0.00002 to 0.0018
creaobs[tolower(unittype) %in% "mmol/l" &
value < 0.0018 & value > 0.00002,
.N] #there are 0 of these
#same range in mg/dl is 0.00002 to 0.0018
creaobs[tolower(unittype) %in% "mg/dl" &
value < 20.34 & value > 0.226,
.N] #there are 25 of these
#Just sticking to those within a plausible range, regardless of units
creaobs <- creaobs[value < 1800 & value > 20, ]
rm(micromol)
#adding in patient characteristics needed for formula
creaobs[patient, on = 'patid', `:=` (
gender = i.gender,
dob = i.dob,
black = i.black,
pracid = i.pracid
)]
#pmin/pmax takes the min/max of values in the vector
creaobs[, egfr := 141 * pmin(value * 0.010746 /
ifelse(gender == "M", 0.9, 0.7), 1) ^
ifelse(gender == "M",-0.411,-0.329) *
pmax(
value * ifelse(eventdate < "2014-01-01", 0.010746, 0.011312) /
ifelse(gender == "M", 0.9, 0.7),
1
) ^ -1.209 *
0.993 ^ ((eventdate - dob) / 365.25) *
ifelse(gender == "M", 1, 1.018) *
ifelse(black == 1, 1.159, 1)]
# Using recorded gfr and gfr calc from creatinine
#combi gfr
#select & restrict to eGFR readings (for CKD) <60
#using all the codes from aurum dict that incl "gfr"
eGFRresults <- obstabtest[medcodeid %in% testcodes[
(tolower(term) %like% "gfr" | tolower(term) %like% "glomerular") &
test == "ckd", medcodeid] & !is.na(value) & value > 0 & value < 60,
.(patid, obsid, value, eventdate, descr)]
#Using these 5:
#1:1942831000006114 eGFR using creatinine (CKD-EPI) per 1.73 square metres
#2:976481000006110 GFR calculated abbreviated MDRD
#3:1540241000006111 GFRcalculated abbreviated MDRD adj for African Americ orign
#4:1866321000006117 Estimated GFR using CKD-Epi formula per 1.73 square metres
#5:1942821000006111 eGFR using cystatin C (CKD-EPI) per 1.73 square metres
eGFRresults[, .N, by = descr]
# GFR calculated abbreviated MDRD 606235
# eGFR using creatinine (CKD-EPI) per 1.73 square metres 73429
# eGFR using cystatin C (CKD-EPI) per 1.73 square metres 13
# Estimated GFR using CKD-Epi formula per 1.73 square metres 334
# GFR calculated abbreviated MDRD adj for African Americ orign 3321
eGFRresults[, descr := NULL]
#Changing the creaobs DT to match the structure for binding
creaobs <- creaobs[, .(patid, obsid, eventdate, value = egfr)]
eGFRresults <- rbind(eGFRresults, creaobs)
rm(creaobs)
setkey(eGFRresults, patid, eventdate)
eGFRresultsminmax <- eGFRresults[,
.(max = max(value), min = min(value)),
by = patid]
eGFRresultsminmax[, .N] #560,331 people have egfr results
eGFRresultsminmax[min < 60 &
max >= 60] #93,069 have at least one value >=60
#& at least one value <60
rm(eGFRresultsminmax)
#only interested in values less than 60
eGFR_CKD <- eGFRresults[value < 60,]
#looking at how many people had X numbers of abnormal records
eGFR_CKD[, numobs := .N, by = patid][, .N, keyby = numobs]
uniqueN(eGFR_CKD[, patid]) #118,554 have at least one value <60
#need to have at least 2 values less than 60
eGFR_CKD <- eGFR_CKD[numobs > 1,]
uniqueN(eGFR_CKD[, patid]) #99,807 have at least 2 values <60
setkey(eGFR_CKD, patid, eventdate)
#calculating the number of days between the 1st and last value <60 recorded
time <-
eGFR_CKD[, .(max = max(eventdate), min = min(eventdate)), by = patid]
#getting rid of patients who don't have at least 90 days
#between 1st and last recordings
eGFR_CKD <-
eGFR_CKD[patid %in% time[as.IDate(max) - as.IDate(min) > 90,
patid],]
setkey(eGFR_CKD, patid, eventdate)
rm(time)
firstegrf <- eGFR_CKD[eGFR_CKD[, .I[1], keyby = c("patid")]$V1]
#adding in the date of the 1st <60 value recorded
eGFR_CKD <-
eGFR_CKD[firstegrf, on = 'patid', `:=` (firstobsdate = i.eventdate)]
rm(firstegrf)
#want records 90+ days after the 1st <60 value recorded
eGFR_CKD <-
eGFR_CKD[as.IDate(eventdate) - as.IDate(firstobsdate) > 90,]
setkey(eGFR_CKD, patid, eventdate)
#only need the earliest of recordings after the 90 time frame
eGFR_CKD <- eGFR_CKD[eGFR_CKD[, .I[1], keyby = c("patid")]$V1]