-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPhenotypeTesting.Rmd
6118 lines (4470 loc) · 293 KB
/
PhenotypeTesting.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
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: "Phenotype Testing"
author: "Eugene Gardner"
date: "03 December 2020"
output:
html_document:
toc: true
toc_depth: 2
---
# 1. Startup and Introduction
This document contains UKBB data and comparisons between and within this data to the trait of interest, Fertility. If using data produced by this repo, please cite [our manuscript](https://www.biorxiv.org/content/10.1101/2020.05.26.116111v2).
**Big Note**: The first part of this document involves running scripts to generate text files required for downstream analysis. _PLEASE_ start there and make sure all scripts ran successfully. All scripts for this section are available in the folder `./scripts/` and _will not_ run as part of this document. There are two additional resources that you need to download -- the OMIM morbid map, which requires registration and DDG2P. See the section [on disease genes](#disease_genes) below.
**Big Note**: You also need to have access to UKBiobank, but this script is agnostic to the UKBiobank application number. You should be able to download a bulk phenotype file and, if it contains the correct phenotypes as referred to in the manuscript and in the file `rawdata/phenofiles/fields_to_extract.txt`, you should be able to reproduce our data and figures.
**Big Note**: Due to legacy variable naming, the terms **FI** and **CHOD** are synonymous in this document. FI stands for "first incidence", the internal UKBB name for the term we use in the manuscript: Complete Health Outcomes Data (e.g. CHOD).
You can view a compiled html version of this document with all code run either within this repository at `compiled_htmls/PhenotypeTesting.html` or on [github](https://htmlpreview.github.io/?https://github.com/eugenegardner/UKBBFertility/blob/master/compiled_html/PhenotypeTesting.html).
## 1A. Libraries
```{r setup}
knitr::opts_chunk$set(
echo = TRUE,
message = FALSE,
warning = FALSE ## Warnings turned off to squelch unecessary ggplot noise in kintted document. Have checked all for accuracy.
)
## Quietly Load Libraries
load.package <- function(name) {
suppressMessages(suppressWarnings(library(name, quietly = T, warn.conflicts = F, character.only = T)))
}
load.package("biomaRt") ## Get gene lists we need
load.package("readxl") ## Read Supplemental Excel tables
load.package("data.table") ## Better than data.frame
load.package("patchwork") ## Arranging ggplots
load.package("broom") ## Makes getting covars out of lm much tidier
load.package("meta") ## For doing meta analysis
load.package("mratios") ## Need this to calculate 95% CIs for ratios of two means
load.package("svglite") ## Need to create main text figures properly (ggsave doesn't like anything with an alpha and is .SVG easier to edit in Illustrator)
load.package("tidyverse") ## Takes care of ggplot, tidyr, dplyr, and stringr
load.package("rcompanion") ## For getting incremental pseudo-R2
load.package("lubridate") ## For dealing with participant birthdays
```
## 1B. Themes
Set themes for internal figures just for testing purposes:
```{r Base Themes}
theme <- theme(panel.background=element_rect(fill="white"),line=element_line(size=1,colour="black",lineend="round"),axis.line=element_line(size=1),text=element_text(size=16,face="bold",colour="black"),axis.text=element_text(colour="black"),axis.ticks=element_line(size=1,colour="black"),axis.ticks.length=unit(.1,"cm"),strip.background=element_rect(fill="white"),axis.text.x=element_text(angle=45,hjust=1),legend.position="blank",panel.grid.major=element_line(colour="grey",size=0.5),legend.key=element_blank())
## Default theme w/legend
theme.legend <- theme + theme(legend.position="right")
del.line <- "#4F7942"
del.fill <- "#77DD77"
dup.line <- "#0000FF"
dup.fill <- "#AEC6CF"
```
Theme for main text/supplemental figures (making font size smaller):
```{r Figure Themes}
theme.figures <- theme(panel.background=element_rect(fill="white"),line=element_line(size=1,colour="black",lineend="round"),axis.line=element_line(size=1),text=element_text(size=9,face="bold",colour="black"),axis.text=element_text(colour="black"),axis.ticks=element_line(size=1,colour="black"),axis.ticks.length=unit(.1,"cm"),strip.background=element_rect(fill="white"),axis.text.x=element_text(angle=45,hjust=1),legend.position="blank",panel.grid.major=element_line(colour="grey",size=0.5),legend.key=element_blank())
## Default theme w/legend
theme.figures.legend <- theme.figures + theme(legend.position="right")
## Colour Scheme:
male.col <- "#38BCA0"
female.col <- "#7B06F8"
sex.colours <- c(male.col, female.col)
names(sex.colours) <- c("Male","Female")
sex.colours.fill <- scale_fill_manual(name = "Sex",values=sex.colours,guide=guide_legend(reverse=F))
sex.colours.colour <- scale_colour_manual(name = "Sex",values=sex.colours, guide=guide_legend(reverse=F))
sex.colours.fill.rev <- scale_fill_manual(name = "Sex",values=sex.colours,guide=guide_legend(reverse=T))
sex.colours.colour.rev <- scale_colour_manual(name = "Sex",values=sex.colours, guide=guide_legend(reverse=T))
alt.colours <- c("#75485E","#CB904D","#DFCC74")
```
## 1C. Prepping Storage Directories
This just unpacks the tarball of provided data resources at `rawdata.tar.gz`
```{bash Prepare Storage}
tar -zxf rawdata.tar.gz
```
# 2. Generating Required Text Files
Example code for downloading and initial processing UKBB phenotype file. None of the code in this section will actually be run.
## 2A. Creating Master Phenotype File:
This code chunk is not evaluated here but is provided for replication purposes. This code chunk assumes that the user has already gained access to, and [downloaded](http://biobank.ndph.ox.ac.uk/showcase/), relevant phenotype fields and has aquired the encoded phenotype file (like ukb00000.enc). The tools used below are also available via the [UKBiobank datashowcase website](http://biobank.ndph.ox.ac.uk/showcase/download.cgi). More information on downloading can be found [here](https://biobank.ctsu.ox.ac.uk/~bbdatan/Accessing_UKB_data_v2.1.pdf).
```{bash Get UKBB Phenotype File, eval = F}
## First step involves downloading and decoding individual phenotype data. Keyvalue is the key provided via email when you apply for bulk download. This will create a decoded file ukb00000.enc_ukb
ukbunpack ukb00000.enc <keyvalue>
## Next, convert the file to a tab-delimited format:
ukbconv ukb00000.enc_ukb txt
## Create a data dictionary (so we know where phenotypes are in the file!)
ukbconv ukb00000.enc_ukb docs
## This should result in 2 required files for further processing:
# ukb00000.txt
# ukb00000.html
```
**Note** the following processing data expects the "ukb00000.*" data to be in the unpacked `rawdata/phenofiles/` directory!
This code chunk extracts phenotypes of relevance from the master phenotype file that is downloaded and processed above. It is run with the script: `./scripts/extract_phenotypes.pl`.
This script is slower than it should be due to an issue with text format encoding of the UKBB-created TSV file on MacOS. If running this code on a UNIX system, would suggest switching the 'exec' call at the bottom of this script to use cut for additional speed. It should mean the script executes in ~30s rather than 5mins.
```{bash Extract Phenotypes, eval = F}
## First do most fields:
./scripts/extract_phenotypes.pl rawdata/phenofiles/fields_to_extract.txt rawdata/phenofiles/ukbb_phenotypes.txt
## Have to extract first incidence data seperately as it requires additional processing:
## P.S. Make sure you run the above command first!!!
./scripts/extract_phenotypes.pl rawdata/phenofiles/fi_fields_to_extract.txt rawdata/phenofiles/fi_phenotypes.txt
./scripts/process_first_incidence.pl
```
## 2B. Setting Unrelated Individuals:
Again, this is just an example on how relatedness information is accquired from UKBB, code does not actually run. It proceeds in two basic steps:
1. Download the relatedness file using the (ukbgene)[http://biobank.ndph.ox.ac.uk/showcase/refer.cgi?id=664] tool
2. Place the file in `./rawdata/phenofiles/`
3. Running the provided script to generate a list of individuals to filter - at: `./scripts/get_relateds.R`.
```{bash Process Relatedness, eval = F}
## 1. Run ukbgene rel. This will download a file like: ukbXXXXX_rel_sYYYYYY.dat, where X represents your application ID, and 488288 represents the file version
ukbgene rel
## 2. Get related individuals to filter (change the name of the .dat to your specific file):
./scripts/get_relateds.R ukbXXXXX_rel_sYYYYYY.dat > raw_data/phenofiles/relateds.out
## Format the output file to be readable by R
perl -ne 'if ($_ =~ /\"(\d{7})\"/) {print "$1\n";}' raw_data/phenofiles/relateds.out > raw_data/phenofiles/relateds.txt
```
# 3. Phenotype Data
Read in the master phenotype and related individuals file that was created in [the previous section](#2._generating_required_text_files)
```{r Load Master Phenotype File}
UKBB.raw.phenotypes <- fread("rawdata/phenofiles/ukbb_phenotypes.txt")
UKBB.raw.phenotypes[,eid:=as.character(eid)]
```
```{r Load Relatedness File}
related.individuals <- fread("rawdata/phenofiles/relateds.txt", header = F)
setnames(related.individuals,"V1","eid")
related.individuals[,eid:=as.character(eid)]
```
## 3A. Generic Phenotypes
Grabbing generic phenotypes age, sex, ancestry, European ancestry status and adding them to the main UKBB.phenotype.data table.
This also filters out individuals that are not broadly European.
```{r Process Generic Phenotypes}
## Data table of all UKBB population data:
PCAs<-c(1:40)
for (i in PCAs) {
PCAs[i] <- paste("22009-0",i,sep=".")
}
fields <- c("eid","22006-0.0","31-0.0","21022-0.0","34-0.0","52-0.0",PCAs)
UKBB.phenotype.data <- UKBB.raw.phenotypes[,..fields]
setnames(UKBB.phenotype.data,c(fields),c("eid","white.british.ancestry","sexPulse","agePulse","birth.year","birth.month",paste0("PC",seq(1,40))))
## Remove all non-white British (determined direct by UKBB and taken from the pheno file)
UKBB.phenotype.data <- UKBB.phenotype.data[!is.na(white.british.ancestry)]
paste0("Number of Broadly Euro Indiv: ", table(UKBB.raw.phenotypes[,`22006-0.0`]))
## Remove all related individuals:
UKBB.phenotype.data <- UKBB.phenotype.data[!eid %in% related.individuals[,eid]]
## Change sex to be 1 = male, 2 = female instead of 0,1.
## This is a distinction made for an old project to keep it consistent.
## And remove individuals that have mismatched genetic/reported sex
UKBB.phenotype.data[,sexPulse:=ifelse(sexPulse == 0, 2, 1)]
## Add agePulse.squared covar:
UKBB.phenotype.data[,agePulse.squared:=agePulse^2]
paste0("Number of Individuals after filtering: ",nrow(UKBB.phenotype.data))
## Curate birthdays:
## Have to set everybody's birthday as the 15th since UKBB doesn't want to give specific days out. Should be a reasonable approximation as it's the closest possible day for all individuals...
UKBB.phenotype.data[,birthday:=paste(birth.year,sprintf("%02d",birth.month),"15",sep="-")]
UKBB.phenotype.data[,birthday:=as.Date(birthday, format = "%Y-%m-%d")]
UKBB.phenotype.data[,birth.year.cut:=cut(birth.year, breaks = seq(1930,1970,by=5))]
UKBB.phenotype.data[,birth.month:=NULL]
## Add Fields for Excluding Specific Birth Years:
for (i in c(1940,1950,1960)) {
age.remove <- UKBB.phenotype.data[birth.year < i | birth.year >= (i + 10),eid]
col <- paste0("is.age.",i)
UKBB.phenotype.data[,eval(col):=if_else(eid %in% age.remove, 1, 0)]
}
rm(PCAs,fields,i)
```
## 3B. Recent Ancestry
Accounting for recent ancestry by using IBD segments calculated in [this](https://www.nature.com/articles/s41467-020-19588-x) manuscript. The sparse matrix of IBD sharing is available [here](https://link.tbd). When downloaded, place this file in `rawdata/phenofiles/IBD_GRM_t10.grm.gz`, and the associated IDs file in `rawdata/phenofiles/IBD_GRM_t10.grm.cat.id`.
I am then using egienvalue decomposition on the sparse matrix (similar to [this](https://elifesciences.org/articles/61548) manuscript) to generate 100 PCs from that data. I have provided the script to process the matrix at:
`./scripts/ibd_pca.py`
This script is written in python3 and requires the scipy and pandas modules to be installed to run. This script is merely provided as an example and is not intended to be run as-is. It should take ~45 minutes to generate PCs, which should be moved to to:
`./rawdata/phenofiles/IBD_PCs.txt`
Now we load those PCs in and add to UKBB.phenotype.data
```{r Recent Ancestry}
recent.ancestry.PCs <- fread("rawdata/phenofiles/IBD_PCs.txt", header = F)
setnames(recent.ancestry.PCs,names(recent.ancestry.PCs),c("eid",paste0("rare.PC",seq(1,100))))
recent.ancestry.PCs[,eid:=as.character(eid)]
for (pc in paste0("rare.PC",seq(1,100))) {
new.val <- paste0("scaled.",pc)
recent.ancestry.PCs[,eval(new.val):=scale(get(pc))]
}
cols <- c("eid",paste0("scaled.rare.PC",seq(1,100)))
UKBB.phenotype.data <- merge(UKBB.phenotype.data,recent.ancestry.PCs[,..cols],by="eid", all.x = T)
rm(recent.ancestry.PCs)
```
## 3C. Fertility
```{r Fertility pt 1, fig.height=5, fig.width=4}
fertility.metrics <- UKBB.raw.phenotypes[,c("eid",
"2405-0.0", ## Children Fathered
"2734-0.0", ## Live Births
"6141-0.0", ## Individuals in household
"709-0.0", ## Number of individuals in household
"2129-0.0", ## Answered Sex Questions
"2159-0.0", ## Same sex behaviour
"2139-0.0", ## Age at first sexual intercourse
"31-0.0" ## Sex for other stuff
)]
## Replace all NAs with a double value to make filtering easier
fertility.metrics[is.na(fertility.metrics)] <- -9
setnames(fertility.metrics,names(fertility.metrics),c("eid",
"children.fathered",
"live.births",
"in.household",
"number.in.household",
"answered.sex",
"same.sex",
"age.first.intercourse",
"sexPulse"))
## Just for making plots
fertility.metrics[,sexPulse:=ifelse(sexPulse == 0, 2, 1)]
fertility.metrics[,sexPulse:=factor(sexPulse,levels=c(1,2),labels=c("Male","Female"))]
# Number of live births:
fertility.metrics[,live.births:=if_else(live.births > 7, -9, live.births)]
fertility.metrics[,live.births:=if_else(live.births < 0, -9, live.births)]
ggplot(fertility.metrics[live.births>=0],aes(live.births,..density..)) +
geom_histogram(binwidth = 1,colour="black",fill=female.col) +
xlab("Live Births") +
scale_y_continuous(name = "Proportion of Females", limits=c(0,0.5), labels = paste0(c(0,10,20,30,40,50),"%")) +
theme
# Children fathered
fertility.metrics[,children.fathered:=if_else(children.fathered > 7, -9, children.fathered)]
fertility.metrics[,children.fathered:=if_else(children.fathered < 0, -9, children.fathered)]
ggplot(fertility.metrics[children.fathered>=0],aes(children.fathered,..density..)) +
geom_histogram(binwidth = 1,colour="black",fill=male.col) +
xlab("Children Fathered") +
scale_y_continuous(name = "Proportion of Males", limits=c(0,0.5), labels = paste0(c(0,10,20,30,40,50),"%")) +
theme
## Who is in the household is stored in an array of up to 5 values (so can stored UP to 5 possible relationships)
## Is a follow-up question to "how many individuals are in your household?" and will be NA if they did not answer
## To make this simple, just taking the first response, the followup data is so small, isn't going to matter and it's taking me way too long to come up with all possible combinations
fertility.metrics[,partner.in.house:=if_else(number.in.household < 0,-9, ## Did not answer, did not know, did not want to answer
if_else(number.in.household==1,0, ## individuals living by themselves
if_else(number.in.household > 1 & in.household == 1,1,0)))] ## Check if partner present
fertility.metrics[,lives.alone:=if_else(number.in.household < 0,-9, ## Did not answer, did not know, did not want to answer
if_else(number.in.household==1,0,1))] ## Check if living alone
ggplot(fertility.metrics,aes(as.factor(partner.in.house),group=sexPulse,fill=sexPulse)) +
stat_count(position="identity",alpha=0.5) +
scale_alpha_continuous(range=c(0,1)) +
scale_x_discrete(name="Has Partner In Home?",labels=c("Did Not Answ.","False","True")) +
sex.colours.fill +
theme.legend
## Same sex sexual behaviour
fertility.metrics[,same.sex:=if_else(answered.sex == 1,
if_else(same.sex == 0,0,
if_else(same.sex == 1,1,-9)),
-9)]
ggplot(fertility.metrics,aes(as.factor(same.sex),group=sexPulse,fill=sexPulse)) +
stat_count(position="identity",alpha=0.5) +
scale_alpha_continuous(range=c(0,1)) +
scale_fill_manual(values=c(male.col,female.col),guide=guide_legend(title="Sex"),labels=c("Male","Female")) +
scale_x_discrete(name = "Enganged in Same Sex\nIntercourse", labels = c("NA","False","True")) +
scale_y_continuous(name = "# of Indiv.") +
sex.colours.fill +
theme.legend
```
Separate block so plots don't get stretched out weird.
```{r Fertility pt 2, fig.height=5, fig.width=10}
## Age at first sexual intercourse
# This just modifies the special codes so they spread out on the plot
fertility.metrics[,plot:=ifelse(age.first.intercourse < 0, age.first.intercourse * 5, age.first.intercourse)]
ggplot(fertility.metrics, aes(plot,..density..,group = sexPulse, fill = sexPulse)) +
geom_histogram(binwidth=1, position = position_dodge()) +
scale_x_continuous(name = "Age at First Intercourse", breaks = c(-15,-10,-5,0,10,20,30,40,50,60), labels = c("Prefer not to answer","Never had sex", "Do not know", 0, 10, 20, 30, 40, 50, 60)) +
scale_y_continuous("% Individuals") +
sex.colours.fill +
theme.legend
## Has had sexual intercourse - which is derived from age at first sexual intercourse data
fertility.metrics[,had.sex:=if_else(answered.sex != 1, -9,
if_else(age.first.intercourse == -3 | age.first.intercourse == -1, -9,
if_else(age.first.intercourse == -2, 0, 1)))]
table(fertility.metrics[,c("sexPulse","had.sex")])
prop.table(table(fertility.metrics[,c("sexPulse","had.sex")]),margin = 1) * 100
# Check for immaculate conceptions...
# V1 is children
table(fertility.metrics[sexPulse == "Male",list(if_else(children.fathered>0,1,0),had.sex)][,c("V1","had.sex")])
table(fertility.metrics[sexPulse == "Female",list(if_else(live.births>0,1,0),had.sex)][,c("V1","had.sex")])
## Now convert all the -9s back to NA
fertility.metrics[,num.children:=if_else(sexPulse=="Male",children.fathered,live.births)]
fertility.metrics <- fertility.metrics[,c("eid","children.fathered","live.births","num.children","partner.in.house","lives.alone","same.sex","had.sex")]
fertility.metrics[,children.fathered:=if_else(children.fathered==-9,as.numeric(NA),children.fathered)]
fertility.metrics[,live.births:=if_else(live.births==-9,as.numeric(NA),live.births)]
fertility.metrics[,partner.in.house:=if_else(partner.in.house==-9,as.numeric(NA),partner.in.house)]
fertility.metrics[,lives.alone:=if_else(partner.in.house==-9,as.numeric(NA),lives.alone)]
fertility.metrics[,same.sex:=if_else(same.sex==-9,as.numeric(NA),same.sex)]
fertility.metrics[,had.sex:=if_else(had.sex==-9,as.numeric(NA),had.sex)]
fertility.metrics[,num.children:=if_else(num.children==-9,as.numeric(NA),num.children)]
UKBB.phenotype.data <- merge(UKBB.phenotype.data,fertility.metrics,by="eid")
rm(fertility.metrics)
```
## 3D. Fluid Intelligence
This section looks at UKBB "Fluid Intelligence".
The field of relevance for us is 20016-0.0. There is no array data (only 1 test was done, but 3 instances - we're using instance 0).
```{r Fluid Intelligence}
## Grab fluid intel from the raw phenotypes:
fluid.intel.table <- UKBB.raw.phenotypes[,c("eid","20016-0.0")]
fluid.intel.table[,fluid.intel:=if_else(is.na(`20016-0.0`),as.integer(NA),`20016-0.0`)]
ggplot(merge(UKBB.phenotype.data,fluid.intel.table,by="eid"),aes(fluid.intel,group=as.factor(sexPulse),fill=as.factor(sexPulse))) +
geom_histogram(binwidth = 1, position="identity", alpha = 0.5) +
scale_alpha_continuous(range=c(0,1)) +
scale_fill_manual(values=c(male.col,female.col),guide=guide_legend(title="Sex"),labels=c("Male","Female")) +
scale_x_continuous(name="Fluid Intel Score") +
scale_y_continuous(name = "# of Individuals") +
theme.legend
## Normalize fluid intelligence
fluid.intel.table[,fluid.intel:=(fluid.intel-mean(fluid.intel,na.rm=T))/sd(fluid.intel,na.rm=T)]
ggplot(merge(UKBB.phenotype.data,fluid.intel.table,by="eid"),aes(fluid.intel,group=as.factor(sexPulse),fill=as.factor(sexPulse))) +
geom_histogram(binwidth = 1, position="identity", alpha = 0.5) +
scale_alpha_continuous(range=c(0,1)) +
scale_fill_manual(values=c(male.col,female.col),guide=guide_legend(title="Sex"),labels=c("Male","Female")) +
scale_x_continuous(name="Normalized Fluid Intel Score") +
scale_y_continuous(name = "# of Individuals") +
theme.legend
## Merge with remaining phenotypes
UKBB.phenotype.data <- merge(UKBB.phenotype.data,fluid.intel.table[,c("eid","fluid.intel")],by="eid",all.x=T)
rm(fluid.intel.table)
```
## 3E. Educational Attainment
Analyzing fields for Educational Attainment.
6138-0/1/2 includes educational attainment measures. There are a max of 5 values for each instance (to accomodate multiple levels of qualifications). Weuse a binary for did/did not complete a college degree, which is high correlated with years of education according to [this](https://academic.oup.com/sf/article-abstract/92/1/109/2235872?redirectedFrom=fulltext) article (cannot actually read it as is behind a paywall, but was cited in [this](https://static-content.springer.com/esm/art%3A10.1038%2Fnature17671/MediaObjects/41586_2016_BFnature17671_MOESM48_ESM.pdf) study as an explanation for why they don't care about years schooling vs. college education.
```{r Educational Attainment, fig.height=3, fig.width=6}
educational.attainment <- UKBB.raw.phenotypes[,c("eid","6138-0.0")]
## only have to check the first array column as that is the only one that is ever == 1 (i.e. college education)
educational.attainment[,test.1:=if_else(is.na(`6138-0.0`),as.integer(NA),
if_else(`6138-0.0` == -3,as.integer(NA),
if_else(`6138-0.0` == 1,1L,0L)))]
## This is for just testing in center data
educational.attainment[,completed.college:=test.1]
educational.attainment <- educational.attainment[,c("eid","completed.college")]
ggplot(merge(UKBB.phenotype.data,educational.attainment,by="eid"),aes(as.factor(completed.college),group=as.factor(sexPulse),fill=as.factor(sexPulse))) +
stat_count(position="identity",alpha=0.5) +
scale_alpha_continuous(range=c(0,1)) +
scale_fill_manual(values=c(male.col,female.col),guide=guide_legend(title="Sex"),labels=c("Male","Female")) +
scale_x_discrete(name="Completed College?",labels=c("False","True","NA")) +
theme.legend
## Merge with remaining phenotypes
UKBB.phenotype.data <- merge(UKBB.phenotype.data,educational.attainment,by="eid",all.x=T)
rm(educational.attainment)
```
## 3F. Household Income
```{r Income data}
income.data <- UKBB.raw.phenotypes[,c("eid","738-0.0")]
income.data[,household.income:=if_else(`738-0.0`>0,`738-0.0`,as.integer(NA))]
income.data <- income.data[,c("eid","household.income")]
ggplot(merge(UKBB.phenotype.data,income.data,by="eid"),aes(household.income,group=as.factor(sexPulse),fill=as.factor(sexPulse))) +
geom_histogram(binwidth=1,position=position_dodge(),colour="black") +
scale_fill_manual(values=c(male.col,female.col),guide=guide_legend(title="Sex"),labels=c("Male","Female")) +
scale_x_continuous(name="Income Bracket") +
ylab("# of Individuals") +
theme.legend
## Merge with remaining phenotypes
UKBB.phenotype.data <- merge(UKBB.phenotype.data,income.data,by="eid",all.x=T)
rm(income.data)
```
## 3G. Townsend Deprivation Index
```{r TDI}
tdi.data <- UKBB.raw.phenotypes[,c("eid","189-0.0")]
setnames(tdi.data,"189-0.0","townsend.index")
tdi.data <- tdi.data[!is.na(townsend.index)]
ggplot(merge(UKBB.phenotype.data,tdi.data,by="eid"),aes(townsend.index,..density..,group=as.factor(sexPulse),fill=as.factor(sexPulse))) +
geom_histogram(position="identity",alpha=0.5) +
scale_alpha_continuous(range=c(0,1)) +
scale_fill_manual(values=c(male.col,female.col),guide=guide_legend(title="Sex"),labels=c("Male","Female")) +
scale_x_continuous(name="Townsend Dep. Index") +
scale_y_continuous(name="Proportion of Individuals") +
theme.legend
UKBB.phenotype.data <- merge(UKBB.phenotype.data,tdi.data,by="eid",all.x=T)
rm(tdi.data)
```
## 3G. Email
```{r email data}
email.data <- UKBB.raw.phenotypes[,c("eid","20005-0.0")]
## As far as I can tell this is a purely binary value:
email.data[,has.email:=if_else(!is.na(`20005-0.0`),1,0)]
email.data <- email.data[,c("eid","has.email")]
ggplot(merge(UKBB.phenotype.data,email.data,by="eid"),aes(as.factor(has.email),group=as.factor(sexPulse),fill=as.factor(sexPulse))) +
stat_count(position="identity",alpha=0.5) +
scale_alpha_continuous(range=c(0,1)) +
scale_fill_manual(values=c(male.col,female.col),guide=guide_legend(title="Sex"),labels=c("Male","Female")) +
scale_x_discrete(name="Has Email?",labels=c("False","True")) +
theme.legend
## Merge with remaining phenotypes
UKBB.phenotype.data <- merge(UKBB.phenotype.data,email.data,by="eid",all.x=T)
rm(email.data)
```
## 3H. Mental Health Phenotypes
### ICD 10 Coding
#### Hospital Episode Statistics
This code pulls in all Hospital Episode Statistic (HES) ICD-10 codes for all individuals. Using this to test for
$$ has.children \sim s_{het[i,v]} + has.icd.code + age + age^2 + PC1..PC10 $$
In the section(s) below.
```{r All ICD codings}
## Load most HES ICD-10 Codes except cancer
cols <- names(UKBB.raw.phenotypes)[grep("eid|41202|41204",names(UKBB.raw.phenotypes))]
hes.data.long <- data.table(pivot_longer(UKBB.raw.phenotypes[,..cols],-eid,values_to="icd.code",values_drop_na = T))
hes.data.long <- hes.data.long[,c("eid","icd.code")]
## Remove duplicate primary/secondary codes:
hes.data.long <- unique(hes.data.long)
## Remove any cancer codes that we will get from cancer-specific icd.data
hes.data.long <- hes.data.long[grepl("C",icd.code) == F & grepl("D[0-4]", icd.code, perl = T) == F & grepl("O0", icd.code, perl = T) == F]
## Load Cancer codings:
cols <- names(UKBB.raw.phenotypes)[grep("eid|40006",names(UKBB.raw.phenotypes))]
cancer.data.long <- data.table(pivot_longer(UKBB.raw.phenotypes[,..cols],-eid,values_to="icd.code",values_drop_na = T))
cancer.data.long <- cancer.data.long[,c("eid","icd.code")]
## Mash together regular ICD10 and Cancer codes:
hes.data.long <- rbind(hes.data.long, cancer.data.long)
## Generate shorter string to match:
hes.data.long[,icd.category:=substr(icd.code,1,3),by=1:nrow(hes.data.long)]
rm(cancer.data.long)
```
#### Complete Health Outcomes Data (CHOD) ICD Codings
We have access to the complete health outcomes ICD-10 codings, which we hope will represent a more accurate depiction of conditions an individual has, as well as provide a way of only testing individuals with conditions prior to child-bearing age. We extract fields the same way as before, and then create a data dictionary to link up each code to it's relevant UKBB field. This will incorporate all UKBB fields from 130000-132605. We also incorperate field 42040 here to exclude individuals who don't have GP records. This cuts our sample size in half, but is better than having differential ascertainment in my opinion.
**Note**: Remember that we generated the `fi_phenotypes.txt` and `valid_fi_indvs.txt` files above in section 2A.
```{r read and process}
raw.CHOD <- fread("rawdata/phenofiles/fi_phenotypes.txt")
raw.CHOD[,eid:=as.character(eid)]
valid.CHOD.indvs <- fread("rawdata/phenofiles/valid_fi_indvs.txt")
valid.CHOD.indvs[,eid:=as.character(eid)]
## It's yo birthday!
processed.CHOD <- merge(raw.CHOD,UKBB.phenotype.data[,c("eid","birthday")],by="eid")
processed.CHOD[,date:=as.Date(date, format = "%Y-%m-%d")]
## Set a flag in the phenotype data for people I should include when doing GP-only analyses:
UKBB.phenotype.data[,has.gp.data:=if_else(eid %in% valid.CHOD.indvs[!is.na(num.gp.codes),eid], 1, 0)]
## Get ~age of incidence while taking into account special codes:
processed.CHOD[,age.at.incidence:=if_else(date == as.Date("2037-07-07"), -1, ## This is an error code for incidence in the future and is presumably an error.
if_else(date == as.Date("1901-01-01"), -1, ## This is an error code for incidence before birth (doesn't appear to be any...?)
if_else(date == as.Date("1902-02-02"), 0, ## This is congenital conditions
if_else(date == as.Date("1903-03-03"), 0.5, ## This is for neonatal conditions
time_length(difftime(date, birthday), "years")))))] ## This is for all other cases.
```
This is just to generate equivalent data from CHOD data as is generated for HES and MHQ data.
```{r translate to table format}
## This is very ugly but was the easiest way for me to tabulate it from another datasource to ensure rough concistency with HES/MHQ data
codes <- c("F20","F23","F25",
"F84",
"F30","F31",
"F32","F33",
"F50",
"F40",
"F42",
"F41",
"F60","F61",
"F90",
"N46",
"F70","F71","F72","F78","F79","F80","F81","F82","F89")
condition <- c("scizo","scizo","scizo",
"asd",
"bipolar","bipolar",
"depression","depression",
"eating_disorders",
"phobia",
"ocd",
"gen_anxiety",
"gen_personality","gen_personality",
"add",
"infertility",
"developmental_disorder","developmental_disorder","developmental_disorder","developmental_disorder","developmental_disorder","developmental_disorder","developmental_disorder","developmental_disorder","developmental_disorder")
condition.key <- data.table(code=codes, table.condition=condition)
condition.key <- unique(condition.key)
raw.CHOD <- merge(raw.CHOD, condition.key, by = "code", all.x = T)
condition.table <- data.table(table(raw.CHOD[,c("eid","table.condition")]))
condition.table[,N:=if_else(N == 0, 0, 1)]
condition.table <- data.table(pivot_wider(condition.table, id_cols = eid, names_from=table.condition, values_from = N))
setnames(condition.table,names(condition.table)[-1],paste("fi",names(condition.table)[-1],sep="."))
## This just makes sure every individual we have CHOD data for is in our final table
condition.table <- merge(valid.CHOD.indvs[,c("eid")],condition.table,by="eid",all.x=T)
condition.table[is.na(condition.table)] <- 0
UKBB.phenotype.data <- merge(UKBB.phenotype.data,condition.table[,c("eid","fi.scizo","fi.bipolar","fi.asd","fi.add","fi.developmental_disorder")],by="eid",all.x=T)
rm(raw.CHOD)
```
#### Specific HES ICD-10 Codings
The ICD-10 codes that I have used and their equivalancies to the MHQ section are listed in the perl script below. For the traits covered in [Power et al.](https://jamanetwork.com/journals/jamapsychiatry/article-abstract/1390257) I have stuck with their exact codes to enable replication, for the others I have searched for equivalents using various articles on those particular subjects.
This set of data needs to be processed in two steps, as I use perl to process the actual phenotypes (it's much easier than in R). Need to first print out a text file of the raw phenotypes I need, process it with Perl, and then read back in and add to the final phenotype table.
```{r Print ICD10 Data}
cols.to.print <- c("eid",names(UKBB.raw.phenotypes)[grep("41202",names(UKBB.raw.phenotypes))],names(UKBB.raw.phenotypes)[grep("41204",names(UKBB.raw.phenotypes))])
icd.data <- UKBB.raw.phenotypes[,..cols.to.print]
write.table(icd.data,file="rawdata/phenofiles/ICD10.data.txt",sep="\t",row.names=F,col.names=F,quote=F)
rm(icd.data)
```
```{bash Process ICD10 Data}
./scripts/process_icd.pl
```
```{r process ICD10}
hes.data <- fread("rawdata/phenofiles/ICD10.data.processed.txt")
hes.data[,eid:=as.character(eid)]
setnames(hes.data, names(hes.data), c("eid",paste("hes",names(hes.data)[2:length(names(hes.data))],sep=".")))
UKBB.phenotype.data <- merge(UKBB.phenotype.data,hes.data[,c("eid","hes.scizo","hes.bipolar","hes.asd","hes.add","hes.developmental_disorder")],by="eid",all.x=T)
```
### Mental Health Questionnaire
This [recent paper](https://doi.org/10.1192/bjo.2019.100) documents the mental health questionaire that was sent out to a subset of UKBB particpants. ~160k responded on a number of measures. On the UKBB Data Showcase, they have a [document](http://biobank.ndph.ox.ac.uk/showcase/showcase/docs/mental_health_online.pdf) about what questions were asked and where to find them in the showcase.
This section is attempting to replicate the general codings of [this](https://jamanetwork.com/journals/jamapsychiatry/article-abstract/1390257) study that looked at all Swedish individuals born from 1950-1970 that did not have any genetic data. As such, the equivalent UK Biobank fields and their codings withing the MH Questionnaire are:
* 20406 (alcohol), 20503 (prescription meds), 20456(rec. drugs) - Substance Addiction. Field 20401 indicates a 'YES' answer to ever addicted to a substance or behaviour, which is a 'gate' question to answer these three fields.
* 20544: Numbers that follow are the code for that disorder
+ Social Anxiety/Phobia (1)
+ Psychotic disorders (2 & 3) - This is also encoded in ICD10 code(s) F20-29. Could get a bigger N by using ICD10 codes?
+ Personality disorders (4)
+ Any other diabling phobia(5)
+ Panic Attacks (6)
+ OCD (7)
+ Bipolar disorder, manic depressive diso., etc. (10)
+ Depression (11)
+ Eating disorders (12,13,16)
+ ASD (14)
+ General Anxiety Disorder(15)
+ Agorophobia (17)
+ ADD/ADHD (18)
+ Did not answer one or both sections (-818, -819)
Processing of MH Traits functions similarly to ICD10 above, where I have to print a file, processes with perl and then read it back in:
```{r Print MHQ data}
cols.to.print <- c("eid","20401-0.0","20406-0.0","20456-0.0","20503-0.0",names(UKBB.raw.phenotypes)[grep("20544",names(UKBB.raw.phenotypes))])
mhq.data <- UKBB.raw.phenotypes[,..cols.to.print]
write.table(mhq.data,file="rawdata/phenofiles/mhq.data.txt",sep="\t",row.names=F,col.names=F,quote=F)
rm(mhq.data)
```
```{bash Process MH data}
./scripts/process_mhq.pl
```
```{r Process MHQ}
mhq.data <- fread("rawdata/phenofiles/mhq.data.processed.txt")
mhq.data[,eid:=as.character(eid)]
setnames(mhq.data, names(mhq.data), c("eid",paste("mhq",names(mhq.data)[2:length(names(mhq.data))],sep=".")))
## Convert answered MHQ to binary:
mhq.data[,mhq.answered_mhq:=if_else(is.na(mhq.answered_mhq),0,1)]
UKBB.phenotype.data <- merge(UKBB.phenotype.data,mhq.data[,c("eid","mhq.scizo","mhq.bipolar","mhq.asd","mhq.add","mhq.answered_mhq")],by="eid",all.x=T)
```
### Comparing MH Data Sources
```{r compare MHQ and ICD10, fig.height=8, fig.width=10}
## Totals MHQ:
totals.mhq <- mhq.data[,lapply(.SD, sum,na.rm=T),.SDcols=names(mhq.data)[2:length(names(mhq.data))]]
totals.mhq <- data.table(pivot_longer(totals.mhq,cols=names(totals.mhq),names_sep="\\.",names_to = c(".value","condition")))
## Totals HES:
totals.hes <- hes.data[,lapply(.SD, sum,na.rm=T),.SDcols=names(hes.data)[2:length(names(hes.data))]]
totals.hes <- data.table(pivot_longer(totals.hes,cols=names(totals.hes),names_sep="\\.",names_to = c(".value","condition")))
## Totals CHOD + HES:
totals.fi.hes <- condition.table[,lapply(.SD, sum,na.rm=T),.SDcols=names(condition.table)[2:length(names(condition.table))]]
totals.fi.hes <- data.table(pivot_longer(totals.fi.hes,cols=names(totals.fi.hes),names_sep="\\.",names_to = c(".value","condition")))
## Totals GP only:
totals.fi.gp <- condition.table[eid %in% valid.CHOD.indvs[!is.na(num.gp.codes),eid],lapply(.SD, sum,na.rm=T),.SDcols=names(condition.table)[2:length(names(condition.table))]]
totals.fi.gp <- data.table(pivot_longer(totals.fi.gp,cols=names(totals.fi.gp),names_sep="\\.",names_to = c(".value","condition")))
## Population totals from Sweden
totals.sweden <- data.table(condition = c("add","asd","bipolar","developmental_disorder","scizo"), sweden = c(NA, 2947, 14439, NA, 18890))
n.mhq <- totals.mhq[condition=="answered_mhq",mhq]
n.hes <- nrow(hes.data)
n.fi.hes <- nrow(condition.table)
n.fi.gp <- nrow(condition.table[eid %in% valid.CHOD.indvs[!is.na(num.gp.codes),eid]])
n.sweden <- 2356598
totals.mhq[,prop:=(mhq/n.mhq)*100]
totals.hes[,prop:=(hes/n.hes)*100]
totals.fi.hes[,prop:=(fi/n.fi.hes)*100]
totals.fi.gp[,prop:=(fi/n.fi.gp)*100]
totals.sweden[,prop:=(sweden/n.sweden)*100]
setnames(totals.mhq,c("mhq","prop"),c("value.mhq","prop.mhq"))
setnames(totals.hes,c("hes","prop"),c("value.hes","prop.hes"))
setnames(totals.fi.hes, c("fi","prop"),c("value.fi.hes","prop.fi.hes"))
setnames(totals.fi.gp, c("fi","prop"),c("value.fi.gp","prop.fi.gp"))
setnames(totals.sweden, c("sweden","prop"),c("value.sweden","prop.sweden"))
prop.icd10.coding <- merge(totals.mhq, totals.hes,by="condition",all.y = T)
prop.icd10.coding <- merge(prop.icd10.coding, totals.fi.hes, by = "condition", all.x = T)
prop.icd10.coding <- merge(prop.icd10.coding, totals.fi.gp, by = "condition", all.x = T)
prop.icd10.coding <- merge(prop.icd10.coding, totals.sweden, by = "condition", all.x = T)
cond <- c("add","asd","bipolar","developmental_disorder","scizo")
plot.corr <- function(col.x, col.y, show.x, show.y) {
theme.mod <- theme
if (show.x == F) {
theme.mod <- theme.mod + theme(axis.text.x = element_blank())
}
if (show.y == F) {
theme.mod <- theme.mod + theme(axis.text.y = element_blank())
}
ggplot(prop.icd10.coding[condition %in% cond],aes(get(col.x),get(col.y))) +
geom_point() +
scale_x_log10(name = "", limits=c(1e-3,1e0)) +
scale_y_log10(name = "", limits=c(1e-3,1e0)) +
geom_text(aes(label=condition),size = 5,nudge_x = -0.1, hjust = 1) +
geom_abline(linetype = 2, colour = "red") +
theme.mod
}
blank.text <- grid::textGrob("")
wrap_elements(blank.text) + grid::textGrob("MHQ Prop.") + grid::textGrob("HES Prop.") + grid::textGrob("CHOD w/HES Prop.") +
grid::textGrob("HES Prop.", rot = 90) + plot.corr("prop.mhq", "prop.hes", F, T) + plot_spacer() + plot_spacer() +
grid::textGrob("CHOD w/HES\nProp.", rot = 90) + plot.corr("prop.mhq", "prop.fi.hes", F, T) + plot.corr("prop.hes", "prop.fi.hes", F, F) + plot_spacer() +
grid::textGrob("Sweden Prop.", rot = 90) + plot.corr("prop.mhq", "prop.sweden", T, T) + plot.corr("prop.hes", "prop.sweden", T, F) + plot.corr("prop.fi.hes", "prop.sweden", T, F) +
plot_layout(ncol = 4, nrow = 4, widths = c(0.15,1,1,1), heights = c(0.1,1,1,1))
format.prop.icd10.coding <- prop.icd10.coding[condition %in% cond]
format.prop.icd10.coding[,mhq:=paste0(sprintf("%0.3f",prop.mhq),"%(", value.mhq, ")")]
format.prop.icd10.coding[,hes:=paste0(sprintf("%0.3f",prop.hes),"%(", value.hes, ")")]
format.prop.icd10.coding[,fi.hes:=paste0(sprintf("%0.3f",prop.fi.hes),"%(", value.fi.hes, ")")]
format.prop.icd10.coding[,fi.gp:=paste0(sprintf("%0.3f",prop.fi.gp),"%(", value.fi.gp, ")")]
format.prop.icd10.coding[,sweden:=paste0(sprintf("%0.3f",prop.sweden),"%(", value.sweden, ")")]
format.prop.icd10.coding[,c("condition","mhq","hes","fi.hes","fi.gp","sweden")]
rm(condition.table)
```
### Adding a Covariate for Any Mental Health Disorder or Infertility Code
```{r MHD Covariate}
## Calculate the 'MHT' binary:
has.mht <- unique(c(UKBB.phenotype.data[mhq.scizo == 1 | mhq.bipolar == 1 | mhq.asd == 1 | mhq.add == 1 | hes.scizo == 1 | hes.bipolar == 1 | hes.asd == 1 | hes.add == 1 | fi.scizo == 1 | fi.bipolar == 1 | fi.asd == 1 | fi.add == 1 | hes.developmental_disorder == 1 | fi.developmental_disorder == 1,eid]))
UKBB.phenotype.data[,mht.binary:=if_else(eid %in% has.mht, 1, 0)]
## Calculate Infertility Codes
ukbb.has.male.infertility <- unique(c(hes.data.long[icd.category == "N46", eid],processed.CHOD[grepl("N46",code), eid]))
UKBB.phenotype.data[,has.male.infertility:=if_else(eid %in% ukbb.has.male.infertility, 1, 0)]
## Any Infertility Code (Male or Female)
UKBB.phenotype.data[,fi.fert:=if_else(sexPulse == 1,
if_else(eid %in% processed.CHOD[grepl("N46",code),eid], 1, 0),
if_else(eid %in% processed.CHOD[grepl("N97",code),eid], 1, 0))]
```
## 3I. Neutral Phenotypes
Purpose of these phenotypes is to provide a test against s[het] for a phenotype we do not expect to have a (strong) genetic component to test to make sure there is no bias in our ascertainment:
* Fresh Fruit Intake (Field 1309)
* Handedness (Field 1707)
* Hair colour (Field 1747)
```{r neutral phenotypes}
neutral.phenos <- UKBB.raw.phenotypes[,c("eid","1309-0.0","1707-0.0","1747-0.0")]
neutral.phenos[,fresh.fruit:=ifelse(is.na(`1309-0.0`),NA,
ifelse(`1309-0.0` < 0,NA,`1309-0.0`))]
neutral.phenos[,handedness:=ifelse(`1707-0.0` == "NaN" | is.na(`1707-0.0`), NA,
ifelse(`1707-0.0`==1,0,
ifelse(`1707-0.0`==2,1,NA)))]
neutral.phenos[,is.blonde:=if_else(is.na(`1747-0.0`) | `1747-0.0` < 0, NaN,
if_else(`1747-0.0` == 1, 1, 0))]
UKBB.phenotype.data <- merge(UKBB.phenotype.data,neutral.phenos[,c("eid","fresh.fruit","handedness","is.blonde")],by="eid",all.x=T)
rm(UKBB.raw.phenotypes)
```
# 4. Assembling Sequencing/Array Data
## 4A. Curating Gene Lists
We use several genelists as part of this project:
1. pLI information from the [gnomAD project](https://storage.googleapis.com/gnomad-public/release/2.1.1/constraint/gnomad.v2.1.1.lof_metrics.by_gene.txt.bgz).
2. s~het~ from [Weghorn et al.](https://doi.org/10.1093/molbev/msz092). The reference file is included in this repository (`rawdata/genelist/shet.weghorn.txt`).
+ We also, for comparative purposes, use the old s~het~ from [Cassa et al.](https://www.nature.com/articles/ng.3831) which is included in this repository as well (`rawdata/genelist/shet.cassa.txt`)
3. ENSEMBL-downloaded resources from [BioMart](https://www.ensembl.org/biomart/martview/0511514c231557b5d24ace4e8f7862e0).
4. Disease genes from ClinVar, DDG2P, and OMIM (see that section for links).
5. Male Infertility Genes from [this paper](https://academic.oup.com/humrep/article/34/5/932/5377831).
The purpose of the following scripts is to generate these lists if they are not available. This process is also duplicated when processing CNV data and annotating SNVs/InDels, as that has to be done as part of a separate script. See both the section on [Variant Data](#4._variant_data) in this document, and the separate RMarkdown documents `CNVCalling_Filtering.R` and `SNVCalling_Filtering.Rmd`, respectively, for more information.
**Note**: These scripts assume you have `curl` installed on your system, which _should_ be true if you are using macos. Please change the scripts below if this is not the case.
### Download Resources from BioMart
```{r Generate biomart resources}
## Hg19
ensembl <- useMart("ensembl", host="http://grch37.ensembl.org", dataset = "hsapiens_gene_ensembl")
hg19.table <- data.table(getBM(attributes = c('ensembl_gene_id','chromosome_name','start_position','end_position','hgnc_id','hgnc_symbol','ensembl_transcript_id'),mart = ensembl))
hg19.table <- hg19.table[!grep("_",chromosome_name)]
write.table(hg19.table,"rawdata/genelists/hg19.genes.txt",col.names=F,row.names=F,quote=F,sep="\t")
## Hg38
ensembl <- useMart("ensembl", dataset = "hsapiens_gene_ensembl")
hg38.table <- data.table(getBM(attributes = c('ensembl_gene_id','chromosome_name','start_position','end_position','hgnc_id','hgnc_symbol','strand'),mart = ensembl))
hg38.table[,hgnc_id:=str_remove(hgnc_id,"HGNC:"),by=1:nrow(hg38.table)]
hg38.table <- hg38.table[!grep("CHR_",chromosome_name)]
write.table(hg38.table,"rawdata/genelists/hg38.genes.txt",col.names=F,row.names=F,quote=F,sep="\t")
rm(hg19.table,hg38.table,ensembl)
```
### s~het~ Gene Lists
```{bash Generate sHET gene lists}
perl -ane 'chomp $_; @F = split("\t", $_); print "$F[0]\t$F[7]\n";' rawdata/genelists/shet.weghorn.txt > rawdata/genelists/shet.processed.weghorn.txt
perl -ane 'chomp $_; @F = split("\t", $_); print "$F[0]\t$F[1]\n";' rawdata/genelists/shet.cassa.txt > rawdata/genelists/shet.processed.cassa.txt
## sHET gene lists (have to attach ENSG):
scripts/matcher.pl -file1 rawdata/genelists/hg19.genes.txt -col1 5 -file2 rawdata/genelists/shet.processed.weghorn.txt -r | perl -ane 'chomp $_; print "$F[2]\t$F[0]\t$F[1]\t$F[6]\n";' > rawdata/genelists/shet.hgnc.txt
scripts/matcher.pl -file1 rawdata/genelists/hg19.genes.txt -col1 5 -file2 rawdata/genelists/shet.processed.cassa.txt -r | perl -ane 'chomp $_; print "$F[2]\t$F[0]\t$F[1]\t$F[6]\n";' > rawdata/genelists/shet.cassa.hgnc.txt
```
### Hg19 Gene Lists
```{bash Generate hg19 Gene Lists}
## Download gnomAD scores:
curl -o rawdata/genelists/gnomad.v2.1.1.lof_metrics.by_gene.txt.bgz https://storage.googleapis.com/gnomad-public/release/2.1.1/constraint/gnomad.v2.1.1.lof_metrics.by_gene.txt.bgz
## Rename your files gnomAD........
mv rawdata/genelists/gnomad.v2.1.1.lof_metrics.by_gene.txt.bgz rawdata/genelists/gnomad.v2.1.1.lof_metrics.by_gene.txt.gz
gunzip -f rawdata/genelists/gnomad.v2.1.1.lof_metrics.by_gene.txt.gz
## Create a reference file of just ENSG and pLI, while removing genes w/o a pLI score:
perl -ane 'chomp $_; @F = split("\t", $_); if ($F[20] ne 'NA') {print "$F[63]\t$F[20]\n";}' rawdata/genelists/gnomad.v2.1.1.lof_metrics.by_gene.txt > rawdata/genelists/hg19.all_genes_with_pli.txt
## Add additional info from biomart that we acquired:
# pLI file:
scripts/matcher.pl -file1 rawdata/genelists/hg19.genes.txt -file2 rawdata/genelists/hg19.all_genes_with_pli.txt -r | perl -ne 'chomp $_; @F = split("\t", $_); print "$F[0]\t$F[3]\t$F[4]\t$F[5]\t$F[6]\t$F[7]\t$F[8]\t$F[1]\n";' > rawdata/genelists/hg19.all_genes_with_pli.2.txt
mv rawdata/genelists/hg19.all_genes_with_pli.2.txt rawdata/genelists/hg19.all_genes_with_pli.txt
# sHET file:
scripts/matcher.pl -file1 rawdata/genelists/hg19.genes.txt -file2 rawdata/genelists/shet.hgnc.txt -r | perl -ne 'chomp $_; @F = split("\t", $_); print "$F[0]\t$F[5]\t$F[6]\t$F[7]\t$F[8]\t$F[9]\t$F[10]\t$F[2]\n";' > rawdata/genelists/hg19.all_genes_with_shet.txt
```
### Hg38 Gene Lists
```{bash Generate hg38 Gene lists}
# Try and match genes to Hg19 based on HGNC ID
# Generate a list of hg19 genes with HGNC IDs:
perl -ane 'chomp $_; if ($F[4] ne "NA" && $F[4] ne "") {print "$F[4]\t$F[0]\t$F[5]\n";}' rawdata/genelists/hg19.genes.txt | sort | uniq > rawdata/genelists/hg19.trans.txt
scripts/matcher.pl -file1 rawdata/genelists/hg19.trans.txt -file2 rawdata/genelists/hg38.genes.txt -col2 4 -r | perl -ane 'chomp $_; print "$F[0]\t$F[1]\t$F[2]\t$F[3]\t$F[4]\t$F[5]\t$F[8]\n";' > rawdata/genelists/hg38.hgnc.matched.txt
# Ask which genes have a pLI score:
scripts/matcher.pl -file1 rawdata/genelists/hg38.hgnc.matched.txt -col1 6 -file2 rawdata/genelists/hg19.all_genes_with_pli.txt -r | perl -ane 'chomp $_; @F = split("\t", $_); print "$F[8]\t$F[9]\t$F[10]\t$F[11]\t$F[12]\t$F[13]\t$F[0]\t$F[7]\n";' > rawdata/genelists/hg38.all_genes_with_pli.txt
# Ask which genes have a sHET score:
scripts/matcher.pl -file1 rawdata/genelists/hg38.hgnc.matched.txt -col1 6 -file2 rawdata/genelists/hg19.all_genes_with_shet.txt -r | perl -ane 'chomp $_; @F = split("\t", $_); print "$F[8]\t$F[9]\t$F[10]\t$F[11]\t$F[12]\t$F[13]\t$F[0]\t$F[7]\n";' > rawdata/genelists/hg38.all_genes_with_shet.txt
# There is a fairly large caveat here, which is that I label the genes with their Hg19 ENSG ID so that I can be consistant in my R code below!!! This does't impact too many genes, they mostly have the same IDs (~2-300)
# This gets a translatable list to hg19 ENSG###:
perl -ne 'chomp $_; @F = split("\t", $_); print "$F[0]\t$F[6]\n";' rawdata/genelists/hg38.all_genes_with_pli.txt > rawdata/genelists/hg38_to_hg19_ENSG.txt
perl -ne 'chomp $_; @F = split("\t", $_); print "$F[0]\t$F[6]\n";' rawdata/genelists/hg38.all_genes_with_shet.txt >> rawdata/genelists/hg38_to_hg19_ENSG.txt
sort rawdata/genelists/hg38_to_hg19_ENSG.txt | uniq > rawdata/genelists/hg38_to_hg19_ENSG.2.txt
mv rawdata/genelists/hg38_to_hg19_ENSG.2.txt rawdata/genelists/hg38_to_hg19_ENSG.txt
```
### Disease Genes
This section of the document is not evaluated, as we need to acquire disease gene resources from three locations. The actual acquisition of these files is trivial, but did not want to attempted to make reproduceable due to potential links breaking. If this section needs to be reproduced, download the resources at the _rough_ following locations and run the code in this section. Otherwise, move to the next section where the file produced by this section has already been generated. Locations to place necessary files and file dates used in the manuscript are listed below:
1. Clinvar - https://ftp.ncbi.nlm.nih.gov/pub/clinvar/vcf_GRCh37/archive_2.0/2019/clinvar_20191003.vcf.gz
+ `rawdata/genelists/clinvar.vcf.gz`
+ date: October 3, 2019
2. DDG2P - http://www.ebi.ac.uk/gene2phenotype/downloads/DDG2P.csv.gz
+ `rawdata/genelists/DDG2P.csv`
+ date: November 12, 2019
3. OMIM - https://www.omim.org/downloads
+ `rawdata/genelists/morbidmap.txt`
+ date: October 8, 2019
**Note**: To download OMIM morbid map you will need to register and place a copy of this file at: `rawdata/genelists/morbidmap.txt`
```{r Process Disease Genes, eval = F}
## Clinvar
clinvarVCFfiltered <- read_tsv("rawdata/genelists/clinvar.vcf.gz", comment = '#', col_names = F, col_types = 'cccccccccccccc') %>%
mutate(PHEN = str_remove(str_extract(X8, 'CLNDN=[^;]*;'), "CLNDN=")) %>%
mutate(PHEN = str_remove(PHEN, "not_provided")) %>%
mutate(PHEN = str_remove(PHEN, "|")) %>%
mutate(PHEN = str_remove(PHEN, ";")) %>%
filter(PHEN != '') %>%
mutate(GENE = str_remove(str_extract(X8, 'GENEINFO=[^;]*:'), "GENEINFO=")) %>%
mutate(CLNSIG = str_remove(str_extract(X8, 'CLNSIG=[^;]*;'), "CLNSIG=")) %>%
filter(CLNSIG %in% c("Pathogenic/Likely_pathogenic;", "Pathogenic;", "Likely_pathogenic;")) %>%
mutate(CLNSIG = str_remove(CLNSIG, ";")) %>%
mutate(ID = X3) %>%
select(c(X1,X2,ID, PHEN, GENE, CLNSIG)) %>%
drop_na(PHEN, GENE)
clinvarGenes <- clinvarVCFfiltered %>%
select(GENE) %>%
distinct() %>%
transform(GENE = strsplit(GENE, "\\|")) %>%
unnest(GENE) %>%
mutate(GENE = gsub(":.*", "", GENE))
clinvarGenes <- data.table(clinvarGenes)
## DDG2P
ddg2p <- fread("rawdata/genelists/DDG2P.csv") %>%
rename(hgnc_id = `hgnc id`)