-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCox_prep_12_UGU_paper1_April9th2026.R
More file actions
1747 lines (1406 loc) · 55.7 KB
/
Cox_prep_12_UGU_paper1_April9th2026.R
File metadata and controls
1747 lines (1406 loc) · 55.7 KB
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
#Revised script for dementia prediction paper
#by KBW April9th 2026
library (tidyverse)
library (tidyverse)
library(ggplot2)
library(survival)
library(ragg)
library(haven)
library(tidyr)
#first run scripts get NPR_inpatient4 and getCDR..5
#as of Jan24th, run NPR_inpatient4 and getCDR..5 (fixing all DODSDAT)
#the scripts creates dementia diagnoses
source("/safe/data/KBW/get_NPR_inpatient_dementia_diagnoses4.R")
source("/safe/data/KBW/get_CDR_dementia_diagnoses5_jan24th.R")
library (tidyverse)
#my signs: §|~ %>% $ {} [ ]
#NPR_dem_only already contains only
#select(ID, NPR_dementia, NPR_dem_date)
class(NPR_dem_only$NPR_dem_date)
head(NPR_dem_only$NPR_dem_date)
NPR_dem_only <-NPR_dem_only %>%
mutate(NPR_dem_date = as.Date(NPR_dem_date))
CDR_dem <- CDR%>%
select(ID, CDR_dementia, CDR_dem_date, CDR_death_date)
#take earliest dementia_date across sources
dem_all <-NPR_dem_only%>%
full_join(CDR_dem, by = "ID")%>%
mutate(
NPR_dementia = coalesce (NPR_dementia, 0L),
#had mistake here CDR_dmenetia
CDR_dementia =coalesce(CDR_dementia, 0L),
dementia_any =if_else(
NPR_dementia ==1L | CDR_dementia == 1L,
1L, 0L
),
dementia_date = case_when(
NPR_dementia ==1L & CDR_dementia == 1L ~ pmin (NPR_dem_date, CDR_dem_date),
NPR_dementia ==1L ~ NPR_dem_date,
CDR_dementia ==1L ~ CDR_dem_date,
TRUE ~ as.Date (NA_character_)
)
)
table (dem_all$dementia_any)
end_of_follow_up <-as.Date("2025-11-03") #the date Andreas got the registry data
dem_all <-dem_all%>%
mutate(
censor_date = case_when(
!is.na(CDR_death_date) ~ CDR_death_date,
TRUE ~ end_of_follow_up))
#check how many unique cases, n =415
all_dementia <- dem_all%>%
select ("ID", "dementia_any")%>%
filter(dementia_any ==1)%>%
distinct(ID, .keep_all = TRUE)
#read in ugu1948
library (haven)
ugu1948 <-read_sav ("/safe/data/UGU-raw-SPSS/ugu1948_English_v2.4_2024_11_20_LIFE.sav")
#View(ugu1948)
#11945 obs of 386 vars
ugu1948 <-ugu1948%>%
mutate (ID = as.integer (ugukod) )
############take away registry opt-out IDs##########
#as informed of March 12th 2026
#IDs with opt-out-of-registry
#the script registry_opt_out.R creates optout_ids
source("/safe/data/KBW/registry_opt_out.R")
#exclude those who have opted out from ugu1948
ugu1948 <-ugu1948%>%
filter(!ID %in% optout_ids)
ugu1948 <-ugu1948%>%
filter(!ID %in% optout_ids)
#full data
cox_ugu1948 <- ugu1948%>%
left_join(dem_all, by = "ID")
#replace missing dementia_any with 0
cox_ugu1948 <- cox_ugu1948%>%
mutate(
dementia_any = if_else (is.na(dementia_any), 0L, dementia_any)
)
#ensure everyone has a censor_date (death or end_of_follow_up, whichever comes first)
cox_ugu1948 <-cox_ugu1948%>%
mutate(
censor_date = case_when(
!is.na(CDR_death_date) ~ CDR_death_date,
TRUE ~ end_of_follow_up
)
)
##create birth_date using RSYEAR and RSMONTH
#use the 15th of the months as standard mind-month approximation
cox_ugu1948 <- cox_ugu1948%>%
mutate(
birth_month = sprintf("%02d",RSMONTH),
birth_date = as.Date(paste0(RSYEAR, "-", birth_month, "-15"))
)
#define start date (all entered in 1961)
#it says tests took place in the period May8th-27th 1961
cox_ugu1948 <- cox_ugu1948%>%
mutate(start_date = as.Date("1961-05-08"))
#compute start_age
cox_ugu1948 <-cox_ugu1948%>%
mutate(
start_age = as.numeric((start_date-birth_date)/365.25)
)
#######cause of reused personnummere#####
####check that dementia_date is not after CDR_death_date####
#It says FALSE, so we+re clean
any(cox_ugu1948$dementia_date > cox_ugu1948$CDR_death_date, na.rm = TRUE)
#compute end date and end_age(dementia or censoring)
cox_ugu1948 <-cox_ugu1948%>%
mutate(
event_date = if_else(dementia_any ==1L, dementia_date, censor_date),
end_age = as.numeric((event_date -birth_date)/365.25)
)
##########do some stuff on ugu1948 again to prep########
# I will scale the tests again
cox_ugu1948 <- cox_ugu1948%>%
mutate(
z_TS6IITP = as.numeric(scale (TS6IITP)),
z_TS6ISTP = as.numeric(scale (TS6ISTP)),
z_TS6IVOTP = as.numeric(scale (TS6IVOTP)),
)
#and I make sex into 0 and 1, keeping NA where necessary, so here,
#if my raw var RSSEX uses as in codebook 1 = male, 2 = female,
#then I recode, to keep direction consistent, 0 = male (reference), 1 = female
cox_ugu1948 <-cox_ugu1948%>%
mutate(
sex01 =ifelse(RSSEX ==2,1,
ifelse(RSSEX ==1,0, NA))
)
#recode 9s to NA in mother father edu
cox_ugu1948 <- cox_ugu1948 %>%
mutate(
RFSUN4 = na_if(RFSUN4, 9),
RMSUN4 = na_if(RMSUN4, 9)
)
#make mean parental edu, and use either val if one missing
cox_ugu1948 <- cox_ugu1948 %>%
mutate(
parentedu_mean = rowMeans(select(., RFSUN4, RMSUN4), na.rm = TRUE)
)
#standardize parental edu var
cox_ugu1948 <- cox_ugu1948%>%
mutate(
z_parentedu_mean = as.numeric(scale (parentedu_mean)),
)
#some might argue we should correct for 3 tests,
#but they are so related
#so, we do another analysis to alleviate this concern
#Now, instead of testing test1: beta1 =0, test 2; beta2=, test 3: beta3 =0,
#which gives a multiple testing problem, we test one gathered hypothesis
#H0=betaIITP =BetaISTP =BetaIVOTP =0
#against
#H1: at least one of them is not null
#this is an omnibus-likelihood ratio-test
#df =3
#controlling for all other covariates
#avoids multiple testing (it is one hypothesis, not three)
#gives evidence for cognitive ability as a block
#is statistically decent, when subtests are part of one same model
# I filter out make sure we have same dataset on all vars
model_data48 <- cox_ugu1948 %>%
select(ID, dementia_any, sex01, z_parentedu_mean,
z_TS6IITP, z_TS6ISTP, z_TS6IVOTP,
start_age, end_age,) %>%
filter(!is.na(start_age)) %>%
filter(!is.na(end_age)) %>%
filter(!is.na(dementia_any)) %>%
filter(!is.na(sex01)) %>%
filter(!is.na(z_parentedu_mean)) %>%
filter(!is.na(z_TS6IITP))%>%
filter(!is.na(z_TS6ISTP))%>%
filter(!is.na(z_TS6IVOTP))
#my signs: §|~ %>% $ {} [ ]
table (model_data48$sex01)
cox_full <-coxph(formula =
Surv(start_age, end_age, dementia_any) ~
z_TS6IITP + z_TS6ISTP + z_TS6IVOTP +
z_parentedu_mean +sex01,
data = model_data48
)
summary(cox_full)
#now I am making a reduced model w/o cognition:
cox_reduced <-coxph(formula =
Surv(start_age, end_age, dementia_any) ~
z_parentedu_mean +sex01,
data = model_data48
)
summary(cox_reduced)
#then
anova(cox_reduced, cox_full, test = "LRT")
########now do the cox on ugu1948######
library(survival)
#with opt-out excluded, n= 10539, number of events= 287; was N = 10547 w/opt-outs
cox_all <-coxph(formula =
Surv(start_age, end_age, dementia_any) ~
z_TS6IITP + z_TS6ISTP + z_TS6IVOTP +
z_parentedu_mean +sex01,
data = cox_ugu1948
)
summary(cox_all)
########Make HR plot#######
#now make a forest plot of teh standardized effects, figure 1:
#extract ORs and CIs
HRs <-exp(coef(cox_all))
CIs <-exp(confint.default(cox_all))
#make clean dataframe for plotting
#remember I recoded RSSEX, whic was 1= Male, and 2 = female, to 0 = male and 1 is female
plot_df <-data.frame(
Predictor = c("Inductive reasoning", "Spatial ability", "Verbal ability",
"Parental education", "Sex (male vs. female)"),
HR =HRs,
CI_low = CIs [,1],
CI_high = CIs[,2]
)
library (ggplot2)
#inductive on top
plot_df$Predictor <- factor(plot_df$Predictor,
levels = c("Sex (male vs. female)",
"Parental education",
"Verbal ability",
"Spatial ability",
"Inductive reasoning"
))
#I think I want one color for the predictors and one for the covariates, to cheer up the plot also
plot_df$Type <- factor(
c("Cognitive", "Cognitive", "Cognitive",
"Covariate", "Covariate"),
levels = c("Cognitive","Covariate"))
#specify where to put plot
outdir <- "/safe/data/KBW/"
library(ragg)
agg_tiff(
file.path(outdir, "Figure1_HR_plot_600_dpi.tif"),
width = 7,
height =5,
units = "in",
res = 600,
compression ="lzw"
)
print(
ggplot(plot_df, aes(x= Predictor, y = HR, color = Type))+
geom_point(size =3)+
geom_errorbar(aes(ymin = CI_low, ymax = CI_high), width = 0.1, linewidth =0.8) +
geom_hline(yintercept = 1, linetype = "dashed")+
coord_flip()+
theme_classic(base_size =18)+
scale_color_manual(values = c("Covariate" = "#d62728", #red
"Cognitive" = "#1f77b4")) + #blue
labs(title = "Childhood cognitive scores
and dementia risk",
y = "Hazard ratio (per 1SD)",
x = "",
color = ""
))
dev.off()
#add sex interaction
#this model is what we do in the paper
cox_all_sex <-coxph(formula =
Surv(start_age, end_age, dementia_any) ~
z_TS6IITP + z_TS6ISTP + z_TS6IVOTP +
z_parentedu_mean +sex01 +
z_TS6IITP:sex01,
data = cox_ugu1948
)
summary(cox_all_sex)
#########Jan 6th 2026 - try to add their own education######
#Add their own edu in 1990
FOB_1990_data <-read.csv ("/safe/data/RAW_DATA/SCB/FOB/FoB_1990.csv")
#data from 1990 = edu_42 for 1948 and edu_37 for 1953
select_FOB_1990 <- FOB_1990_data%>%
mutate (edu_FOB_1990 = UtbNiva)%>%
select (ID, edu_FOB_1990)
#can check SUN2, SUN3, SUN5, seems also edu-vars (look in codebook)
#using UtbNiva
#distribitions for utbildniva are 1-7 and then 9, check, codebook says:
#"UtbNiva": {
# "Question_label": "Utbildningsnivå",
# "Item_label": "",
# "Response_alternatives":
#"0 = Alla födda efter 1974 och före 1926\
#n1 = Förgymnasial utbildning kortare än 9 år\
#n2 = Förgymnasial utbildning 9 år\
#n3 = Gymnasial utbildning högst 2 år\
#n4 = Gymnasial utbildning längre än 2 år men max 3 år\
#n5 = Eftergymnasial utbildning kortare än 3 år (inkl. 4-årigt gymn.)
#n6 = Eftergymnasial utbildning 3 år eller längre (exkl. forskarutb)
#n7 = Forskarutbildning\n9 = ospecificerad nivå",
#> table (cox_ugu1948$edu_FOB_1990)
#1 2 3 4 5 6 7 9
#1921 1979 2426 1404 1385 1692 76 509
#recode 9 to NA in FOB_1990
select_FOB_1990$edu_FOB_1990[select_FOB_1990$edu_FOB_1990 ==9] <- NA
########precautions for reused personnummer######
#to take out the one (Jan28th) that has swopped personnumer, first in excel file in vault
#and any other such
#I will simply check that none have dem_date of FOB1990 vals after death_date
cox_ugu1948 <- cox_ugu1948%>%
left_join(select_FOB_1990, by = "ID")
table (cox_ugu1948$edu_FOB_1990)
#the following lists all that have edu 1990 but died before in DORS/CDR,
#and it is just this one person
cox_ugu1948[
!is.na(cox_ugu1948$edu_FOB_1990) &
!is.na(cox_ugu1948$CDR_death_date) &
cox_ugu1948$CDR_death_date < as.Date("1990-01-01"),
c("ID", "CDR_death_date", "edu_FOB_1990")
]
#now I will replace such impossible cases with NA in principle (here it is just one)
#post this code in channel, as others may want to use same type of standard in UGU
cox_ugu1948$edu_FOB_1990[
!is.na(cox_ugu1948$edu_FOB_1990) &
!is.na(cox_ugu1948$CDR_death_date) &
cox_ugu1948$CDR_death_date < as.Date("1990-01-01")
] <-NA
#and sanity check for no dementia date after death date in CDR, luckily not the case
#but remember to check same for uGU1953 later
any(cox_ugu1948$dementia_date > cox_ugu1948$CDR_death_date, na.rm = TRUE)
#standardize own edu
cox_ugu1948 <- cox_ugu1948%>%
mutate(
z_edu_FOB_1990 = as.numeric(scale (edu_FOB_1990)),
)
########get descriptoves for those having own edu######
# I filter out make sure we have same dataset on all vars
model_data48_own_edu <- cox_ugu1948 %>%
select(ID, dementia_any, sex01, z_parentedu_mean,
z_edu_FOB_1990,edu_FOB_1990,
z_TS6IITP, z_TS6ISTP, z_TS6IVOTP,
start_age, end_age,) %>%
filter(!is.na(start_age)) %>%
filter(!is.na(end_age)) %>%
filter(!is.na(dementia_any)) %>%
filter(!is.na(sex01)) %>%
filter(!is.na(z_parentedu_mean)) %>%
filter(!is.na(z_edu_FOB_1990)) %>%
filter(!is.na(z_TS6IITP))%>%
filter(!is.na(z_TS6ISTP))%>%
filter(!is.na(z_TS6IVOTP))
table (model_data48_own_edu$edu_FOB_1990)
#Table of midlife education proportions by sex
prop.table(table(model_data48_own_edu$edu_FOB_1990, model_data48_own_edu$sex01), 2)
#add own edu in cox
cox_all_edu <-coxph(formula =
Surv(start_age, end_age, dementia_any) ~
z_TS6IITP + z_TS6ISTP + z_TS6IVOTP +
z_parentedu_mean + z_edu_FOB_1990 +sex01,
data = model_data48_own_edu
)
summary(cox_all_edu)
#######Make higher res figure 2 with own edu Jan 6th for paper########
#make a forest plot of the standardized effects:
#extract ORs and CIs
HRs <-exp(coef(cox_all_edu))
CIs <-exp(confint.default(cox_all_edu))
#make clean dataframe for plotting
#recoded RSSEX, which was 1= Male, and 2 = female, to 0 = male and 1 is female
plot_df <-data.frame(
Predictor = c("Inductive reasoning", "Spatial ability", "Verbal ability",
"Parental education", "Midlife education", "Sex (male vs. female)"),
HR =HRs,
CI_low = CIs [,1],
CI_high = CIs[,2]
)
library (ggplot2)
#inductive top
plot_df$Predictor <- factor(plot_df$Predictor,
levels = c("Sex (male vs. female)",
"Midlife education",
"Parental education",
"Verbal ability",
"Spatial ability",
"Inductive reasoning"
))
#I think I want one color for the predictors and one for the covariates, to cheer up the plot also
plot_df$Type <- factor(
c("Cognitive", "Cognitive", "Cognitive",
"Covariate", "Covariate", "Covariate"),
levels = c("Cognitive","Covariate"))
#specify where to put plot
outdir <- "/safe/data/KBW/"
library(ragg)
agg_tiff(
file.path(outdir, "Figure2_w_own_1990_edu_HR_plot_600_dpi.tif"),
width = 7,
height =5,
units = "in",
res = 600,
compression ="lzw"
)
print(
ggplot(plot_df, aes(x= Predictor, y = HR, color = Type))+
geom_point(size =3)+
geom_errorbar(aes(ymin = CI_low, ymax = CI_high), width = 0.1, linewidth =0.8) +
geom_hline(yintercept = 1, linetype = "dashed")+
coord_flip()+
theme_classic(base_size =18)+
scale_color_manual(values = c("Covariate" = "#d62728", #red
"Cognitive" = "#1f77b4")) + #blue
labs(title = "Childhood cognitive scores,
education and dementia risk",
y = "Hazard ratio (per 1SD)",
x = "",
color = ""
))
dev.off()
cox_all_sex <-coxph(formula =
Surv(start_age, end_age, dementia_any) ~
z_TS6IITP + sex01 +
z_TS6IITP:sex01,
data = cox_ugu1948
)
summary(cox_all_sex)
#makes no sense to do it just on the interaction term
cox_sex_int <-coxph(formula =
Surv(start_age, end_age, dementia_any) ~
z_TS6IITP:sex01,
data = cox_ugu1948
)
summary(cox_sex_int)
#######Now load ugu1953 and merge ######
#LOAD UGU1953
ugu1953 <-read_sav ("/safe/data/UGU-raw-SPSS/ugu1953_English_v2.3_2024-11-20.sav")
#View(ugu1953)
#9929 obs of 270 vars
ugu1953 <-ugu1953%>%
mutate (ID = as.integer (ugukod) )
#exclude those who have opted out from ugu1948
ugu1953 <-ugu1953%>%
filter(!ID %in% optout_ids)
#and I make sex into 0 and 1, keeping NA where necessary
#here, rssex ==1 remains 1, where as 2 becomes 0
#ugu1953 <-ugu1953%>%
# mutate(
# sex01 =ifelse(RSSEX ==1,1,
# ifelse(RSSEX ==2,0, NA))
# )
#and I make sex into 0 and 1, keeping NA where necessary, so here,
#if my raw var RSSEX uses as in codebook 1 = male, 2 = female,
#then I recode, to keep direction consistent, 0 = male (reference), 1 = female
ugu1953 <-ugu1953%>%
mutate(
sex01 =ifelse(RSSEX ==2,1,
ifelse(RSSEX ==1,0, NA))
)
#full data
cox_ugu1953 <- ugu1953%>%
left_join(dem_all, by = "ID")
#replace missing dementia_any with 0
cox_ugu1953 <- cox_ugu1953%>%
mutate(
dementia_any = if_else (is.na(dementia_any), 0L, dementia_any)
)
#ensure everyone has a censor_date (death or end_of_follow_up, whichever comes first)
cox_ugu1953 <-cox_ugu1953%>%
mutate(
censor_date = case_when(
!is.na(CDR_death_date) ~ CDR_death_date,
TRUE ~ end_of_follow_up
)
)
##create birth_date using RSYEAR and RSMONTH
#use the 15th of the months as standard mind-month approximation
cox_ugu1953 <- cox_ugu1953%>%
mutate(
birth_month = sprintf("%02d",RSMONTH),
birth_date = as.Date(paste0(RSYEAR, "-", birth_month, "-15"))
)
#define start date (all entered in 1966)
#it says tests took place in the period May8th-27th 1966????
cox_ugu1953 <- cox_ugu1953%>%
mutate(start_date = as.Date("1966-05-09"))
#compute start_age
cox_ugu1953 <-cox_ugu1953%>%
mutate(
start_age = as.numeric((start_date-birth_date)/365.25)
)
#compute end date and end_age(dementia or censoring)
cox_ugu1953 <-cox_ugu1953%>%
mutate(
event_date = if_else(dementia_any ==1L, dementia_date, censor_date),
end_age = as.numeric((event_date -birth_date)/365.25)
)
# I will scale the tests within cohort
cox_ugu1953 <- cox_ugu1953%>%
mutate(
z_TS6IITP = as.numeric(scale (TS6IITP)),
z_TS6ISTP = as.numeric(scale (TS6ISTP)),
z_TS6IVOTP = as.numeric(scale (TS6IVOTP)),
)
#######cause of reused personnummere#####
####check that dementia_date is not after CDR_death_date####
#It says FALSE, so we+re clean
any(cox_ugu1953$dementia_date > cox_ugu1953$CDR_death_date, na.rm = TRUE)
#add missing columns from 1948 into 1953 as NA, without adding new data
#taht did not work, damn!
#vars_1948 <-names (ugu1948)
#ugu1953 <-ugu1953%>%
# mutate (across(setdiff(vars_1948, names(.)),~ NA ))
#Just take the overlapping columns then
common_cols <-intersect(names(cox_ugu1948), names(cox_ugu1953))
ugu1948_small <-cox_ugu1948 %>% select(all_of(common_cols))
ugu1953_small <-cox_ugu1953 %>%select(all_of(common_cols))
ugu_merged <-bind_rows(ugu1948_small, ugu1953_small)
#note, there are a series of conflicting labels when merging, use below to see
warnings() #seems OK to ignore for now, but read up on this!
#maybe best not to restandardize TS6IITP across cohorts
#Cox_ugu4853z <- ugu_merged%>%
# mutate(
# z_TS6IITP = as.numeric(scale (TS6IITP)),
# z_TS6ISTP = as.numeric(scale (TS6ISTP)),
# z_TS6IVOTP = as.numeric(scale (TS6IVOTP)),
# )
Cox_ugu4853x <- ugu_merged
cox_all_merged <-coxph(formula =
Surv(start_age, end_age, dementia_any) ~
z_TS6IITP + z_TS6ISTP + z_TS6IVOTP,
data = Cox_ugu4853x
)
summary(cox_all_merged)
cox_all_merged <-coxph(formula =
Surv(start_age, end_age, dementia_any) ~
z_TS6IITP + z_TS6ISTP + z_TS6IVOTP + sex01,
data = Cox_ugu4853x
)
summary(cox_all_merged)
cox_all_merged <-coxph(formula =
Surv(start_age, end_age, dementia_any) ~
z_TS6IITP + sex01,
data = Cox_ugu4853x
)
summary(cox_all_merged)
##########test if non-linear in merged cohort#####
#there is no significant smooth effect of inductive reasoning on dementia risk
model_data4853 <- Cox_ugu4853x %>%
select(ID, dementia_any, TS6IITP, sex01) %>%
filter(!is.na(dementia_any)) %>%
filter(!is.na(sex01)) %>%
filter(!is.na(TS6IITP))
# now n= 19919, number of events= 367 (n was 19942)
#is significant
model_data4853z <- Cox_ugu4853x %>%
select(ID, dementia_any, z_TS6IITP, sex01) %>%
filter(!is.na(dementia_any)) %>%
filter(!is.na(sex01)) %>%
filter(!is.na(z_TS6IITP))
library (mgcv)
#is there a non-linear effect (smooth) across both cohorts?
#note taht here we do no use standardized scores
model_gam_large <-gam(dementia_any ~s(TS6IITP),
data = model_data4853,
family = binomial)
summary(model_gam_large)
#if we do use standardized scores, the smooth term is not significant
model_gam_large_z <-gam(dementia_any ~s(z_TS6IITP),
data = model_data4853z,
family = binomial)
summary(model_gam_large_z)
#simple fig, looks like hell, but clear, quite linear this
#surprises me actually, may be Swedes are more linear than Norwegians, I wonder why...
plot (model_gam_large, shade = TRUE, rug = TRUE)
#this is obvious, but I have to do a formal test for the ms, I think
#compare to logistic linear model
model_lin_large <-glm(dementia_any ~ TS6IITP,
data = model_data4853,
family = binomial)
anova(model_lin_large, model_gam_large, test = "Chisq")
#make nicer plot for paper
tiff("/safe/data/KBW/Log_odds.tiff", width=6, height=5, units = "in", res = 600)
par(mar = c(5,5,4,2), cex =1.4, cex.lab = 1.6, cex.axis = 1.4)
plot (model_gam_large,
shade = TRUE,
shade.col = "gray90",
rug = FALSE,
seWithMean= TRUE,
xlab = "Childhood inductive reasoning",
ylab = "Smooth effect on log-odds of dementia",
main = "",
bty = "n",
ylim = c(-0.7, 0.7),
scheme =1)
dev.off ()
getwd()
#####Make Figure 3 600dpi#####
outdir <- "/safe/data/KBW/"
library (ragg)
agg_tiff(
file.path(outdir, "Figure3_smooth_600_dpi.tif"),
width = 7,
height =5,
units = "in",
res = 600,
compression ="lzw"
)
par(
mar = c(5,8,4,2),
cex =1.4,
cex.lab = 1.6,
cex.axis = 1.4)
plot (model_gam_large,
shade = TRUE,
shade.col = "gray90",
rug = FALSE,
seWithMean= TRUE,
xlab = "Childhood inductive reasoning",
ylab = "Log-odds of dementia",
main = "",
bty = "n",
ylim = c(-0.7, 0.7),
scheme =1)
dev.off ()
######remake figures with higher resolution#######
#for 1948
model_data1948 <- cox_ugu1948 %>%
select(ID, dementia_any, TS6IITP, TS6ISTP, TS6IVOTP, RSSEX, RFSUN4, RMSUN4, parentedu_mean) %>%
filter(!is.na(dementia_any)) %>%
filter(!is.na(RSSEX)) %>%
filter(!is.na(parentedu_mean)) %>%
filter(!is.na(TS6IITP) & !is.na(TS6ISTP) & !is.na(TS6IVOTP))
#how many females and males in this model (RSSEX: 1 = Male, 2 = female)
table (model_data1948$RSSEX)
#check parent edu in this model
#frequenccies of parental education
table (model_data1948$RFSUN4)
table (model_data1948$RMSUN4)
summary (model_data1948$parentedu_mean)
sd (model_data1948$parentedu_mean)
#show the subtest correlations
cor(model_data1948$TS6IITP, model_data1948$TS6ISTP, use = "pairwise.complete.obs")
cor(model_data1948$TS6IITP, model_data1948$TS6IVOTP, use = "pairwise.complete.obs")
cor(model_data1948$TS6IVOTP, model_data1948$TS6ISTP, use = "pairwise.complete.obs")
#plot the distributions of scores from the subtests
library (ggplot2)
library (tidyr)
model_data1948_long <-model_data1948%>%
select (TS6IVOTP, TS6ISTP, TS6IITP)%>%
pivot_longer(everything(), names_to = "Test", values_to = "Score")%>%
mutate(Test = recode(Test,
"TS6IVOTP" = "Verbal",
"TS6ISTP" = "Spatial",
"TS6IITP" = "Inductive"))
#specify where to put plot
outdir <- "/safe/data/KBW/"
tiff(
file.path(outdir, "subtest_distributions_age13.tif"),
width = 7,
height =5,
units = "in",
res = 300,
compression ="lzw"
)
print(
ggplot(model_data1948_long, aes(x= Score, fill = Test, color =Test))+
geom_density(alpha = 0.3, size =1)+
labs(x = "Test score",
y = "Density",
title = "Distribution of subtest scores, age 13")+
scale_fill_brewer(palette = "Dark2")+
scale_color_brewer(palette ="Dark2")+
theme_minimal(base_size =14)+
theme(
panel.grid = element_blank(),
panel.border =element_blank(),
axis.line = element_line(),
plot.title =element_text(size =16, face = "bold")
))
dev.off()
#or use ragg (for better text rendering?)
library(ragg)
agg_tiff(
file.path(outdir, "subtest_distributions_age13_600_dpi.tif"),
width = 7,
height =5,
units = "in",
res = 600,
compression ="lzw"
)
print(
ggplot(model_data1948_long, aes(x= Score, fill = Test, color =Test))+
geom_density(alpha = 0.3, size =1)+
labs(x = "Test score",
y = "Density",
title = "Distribution of subtest scores, age 13")+
scale_fill_brewer(palette = "Dark2")+
scale_color_brewer(palette ="Dark2")+
theme_minimal(base_size =14)+
theme(
panel.grid = element_blank(),
panel.border =element_blank(),
axis.line = element_line(),
plot.title =element_text(size =16, face = "bold")
))
dev.off()
##now do som additional numbers for Lancet Helathy Longevity version Dec 21st
#check who has dementia from which source across all registry data, total cases seems 403
#check overlap for groups,
#the blow shows that aomng teh 415 cases identified in all of UGU cross cohorts,
#inldung thsoe with other missing daat (so irrespectove of cognitive tests)
#329 were in Ugu48, of which 276 in NPR, and 53 in CDR only
#86 were in UGU53, of which 8 in CDR only,
#but remember, when doing teh merged analysis, we only have 376 dementia cases
"So for uG1948"
# 0-0, not in either,
#0-1: 53 have no dementia in NPR, have in CDR only
# 1-0: 58: have dementia in NPR and not CDR,
# 1-1:97 overlap, have in both;
# 1-NA: 121: have dementia in NPR, no CDR data (likely still alive at end of follow-u)
#NA-NA: 8795 -no info in either registry, people never Hospitalized for dementia/nit died/no dementia recorded at death
#(NPR only:228) NA-1 (CDR only: 61) NA-NA (none of them:4366)
table (paste (cox_ugu1948$NPR_dementia,
cox_ugu1948$CDR_dementia,
sep="-"))
# for ugu53, corresponding numbers are:
#0-1:1532, 0-1:8, 1-0: 15, 1-1:29, 1-NA:34, NA-NA 8309
table (paste (cox_ugu1953$NPR_dementia,
cox_ugu1953$CDR_dementia,
sep="-"))
#in full sample, regardless of cognitives tests
#of 11945 ugu48, 329 dementia cases and 11616 no
#of 9927 in ugu53, 86 dementia cases, and 9841 no
table (cox_ugu1948$dementia_any)
table (cox_ugu1953$dementia_any)
# check w/o missings:
model_data1948 <- cox_ugu1948 %>%
select(ID, dementia_any, TS6IITP, TS6ISTP, TS6IVOTP, RSSEX, RFSUN4, RMSUN4,
NPR_dementia, CDR_dementia, parentedu_mean) %>%
filter(!is.na(dementia_any)) %>%
filter(!is.na(RSSEX)) %>%
filter(!is.na(parentedu_mean)) %>%
filter(!is.na(TS6IITP) & !is.na(TS6ISTP) & !is.na(TS6IVOTP))
table (model_data1948$dementia_any)
table (paste (model_data1948$NPR_dementia,
model_data1948$CDR_dementia,
sep="-"))
# check w/o missing TS6IITP and parent edu:
model_data1948b <- cox_ugu1948 %>%
select(ID, dementia_any, TS6IITP, TS6ISTP, TS6IVOTP, RSSEX, RFSUN4, RMSUN4,
NPR_dementia, CDR_dementia, parentedu_mean) %>%
filter(!is.na(dementia_any)) %>%
filter(!is.na(RSSEX)) %>%
filter(!is.na(TS6IITP))
table (model_data1948b$dementia_any)
table (paste (model_data1948b$NPR_dementia,
model_data1948b$CDR_dementia,
sep="-"))
#check for ugu1953
model_data1953 <- cox_ugu1953 %>%
select(ID, dementia_any, TS6IITP, RSSEX,
NPR_dementia, CDR_dementia) %>%
filter(!is.na(dementia_any)) %>%
filter(!is.na(RSSEX)) %>%
filter(!is.na(TS6IITP))
table (model_data1953$dementia_any)
table (paste (model_data1953$NPR_dementia,
model_data1953$CDR_dementia,
sep="-"))
#check which version of R, is 4.3.3 (2024-02-29)
R.version.string
##########after Lancet desk rejection, do some checks for possible add ons ######
#first, we can considier adding parental edu for ugu1953
#will not be a real value, and no reason for rejection, bu still
#fix parental_edu also with different variable sin ugu1953
#recode 0s = no response to NA in father (QS68) and mother (QS69) edu
ugu1953 <- ugu1953 %>%
mutate(
QS68 = na_if(QS68, 0),
QS69 = na_if(QS69, 0)
)
#make mean parental edu, and use either val if one missing
#note that here, primary school = 1, junior secondary school =2,
#graduated or equivalent = 3, academic degree = 4, check: can it be directly comparable to 1948?
ugu1953 <- ugu1953 %>%
mutate(
parentedu_mean = rowMeans(select(., QS68, QS69), na.rm = TRUE)
)
#standardize parental edu var
ugu1953 <- ugu1953%>%
mutate(
z_parentedu_mean = as.numeric(scale (parentedu_mean)),
)
##########Add analyses on other somatic morbidities for JAMA ######
# I have run KBW_Charlson_R... and saved teh data, now I load that
charlson <-read.csv ("/safe/data/KBW/charlsondata.csv")
names(charlson)
#check
table (charlson$CCIunw, useNA="ifany")
table (charlson$CCIw, useNA="ifany")
#compute CCI-nodemntia
charlson$CCI_nodementia <- charlson$CCIunw - charlson$Dementia
charlson$CCI_event_nodementia <-ifelse (charlson$CCI_nodementia >0,1,0)
table (charlson$CCI_event_nodementia)
#merge, keeping all 1948 cases
cox_ugu1948 <-merge(
cox_ugu1948,
charlson,
by = "ID",
all.x =TRUE
)
#I need to get end_age for charlson non-dementia events
#first identify all non-dementia date columns
#my signs: §|~ %>% $ {} [ ] \\
#list all date vars
date_vars <-names(cox_ugu1948)[grepl("^date\\.", names(cox_ugu1948))]
date_vars
#remove dementia
date_vars_nodementia <- date_vars [date_vars != "date.Dementia"]
#compute earliest non-dementia date
cox_ugu1948$first_CCI_date <-