-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathback-pain.R
2331 lines (1774 loc) · 69.2 KB
/
back-pain.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
# ---- libs ----
suppressPackageStartupMessages(suppressWarnings({
library("dplyr") # tidyverse
library("tidyr")
library("readr")
library("forcats")
library("ggplot2")
library("GGally") # additional ggplot-type plotting
library("compositions")
library("zCompositions") # this one for lr_EM
library("performance") # model checking
library("mice") # missing data functions
library("car") # Anova() for comparing models
library("knitr") # kable() for pretty printing
library("foreach") # powerful looping
library("boot") # bootstrap confidence intervals
library("tictoc") # check time between tic() and toc()
}))
# ---- notes ----
# Introduction
# I want to perform compositional isotemporal substitution based on
# binary regression. I would like to ask for a review of this R script.
# I want to observe results expressed in odds ratios (OR).
# Data
# Exposture:
# - Time_Sleep: in minutes per day
# - Time_Sedentary: in minutes per day
# - Time_LPA: in minutes per day
# - Time_MVPA: in minutes per day
# There were 4 low back pain questions:
#
# Question 1: On how many days have you experienced low back pain in the last 12 months?
# Response options: 0 days / 1-7 days / 8-30 days / 31-90 days / more than 90 days, but not every day / every day
#
# Question 2: How would you rate the average intensity of your low back pain during the last 12 months (average pain intensity on days when you experienced pain)?
# Response options: 0 - 100 (ranging from no pain to worst pain imageable)
#
# Question 3: How intense was the worst low back pain that you experienced in the last month?
# Response options: 0 - 100 (ranging from no pain to worst pain imageable)
#
# Question 4: How intense was the worst low back pain that you experienced in the last week?
# Response options: 0 - 100 (ranging from no pain to worst pain imageable)
#
# Note: Only participants who reported to experience pain in the past 12 months (question 1) were asked to complete the questions 2, 3, and 4.
#
#
# We want to explore the effect of reallocating behaviours on low back pain:
# - occurance (by including all participants into the analysis)
# - frequency (by including only low back pain sufferers into the analysis (ie, those who reported to experience pain in the past 12 months))
# - intensity (by including only low back pain sufferers into the analysis)
#
#
# In case models will not fit, we can compute the outcomes to become a binary outcomes:
#
# Pain intensity could be categorised as (Boonstra et al., 2014):
# - no pain (0)
# - mild pain (1-38)
# - moderate pain (39-57)
# - severe pain (58-100)
#
# Those cut-offs could be used to compute:
# - binary pain occurance outcome (no pain / mild+moderate+severe pain; no pain+mild pain / moderate+severe pain; no pain+mild+moderate pain / severe pain) by including all participants into the analysis
# - binary pain intensity outcome (no pain / mild+moderate+severe pain; no pain+mild pain / moderate+severe pain; no pain+mild+moderate pain / severe pain) by including only low back pain sufferers into the analysis
#
# Binary frequency outcome could be: 1-90 days / more than 90 days (this approximately correspond to: non-chronic pain / chronic pain) by including only low back pain sufferers into the analysis.
# Covariates:
# - sex: sex of the participant. Categorical variable taking one of two categories: female, male.
# - age: age of the participant. Categorical variable taking one of three categories: younger, middle, older.
# - bmi: bmi of the participant. Categorical variable taking one of two categories: normal, overweight.
# - smoking: smoking status of the participant. Categorical variable taking one of two categories: nonsmoker, smoker.
# - stress: stress status of the participant. Categorical variable taking one of two categories: normal, stressed.
# - education: education level of the participant. Categorical variable taking one of two categories: lower, higher.
# - ses: socioeconomic status of the participant. Categorical variable taking one of three categories: lower, middle, higher.
# ---- consts ----
is_sensitivity_analysis <- FALSE
pred_comps <- c("Time_Sleep", "Time_Sedentary", "Time_LPA", "Time_MVPA")
(D <- length(pred_comps))
pred_covs <- c("age", "sex", "bmi", "stress", "smoking", "education", "ses")
outcs <-
c(
"LBP_frequency_year", "LBP_intensity_year",
"LBP_intensity_month", "LBP_intensity_week"
)
# default RHS of model formulas
# (rhs_formula <- paste(c(paste(pred_covs, collapse = " + "), "ilr"), collapse = " + "))
(rhs_formula <- paste(pred_covs, collapse = " + "))
# this is the sequential binary partition matrix to be used for ilr creation
sbp1 <- matrix(
c(
1, 1, -1, -1,
1, -1, 0, 0,
0, 0, 1, -1
),
ncol = 4, byrow = TRUE
)
# a way of creating ilr names automatically from SBP matrix
create_ilr_names <- function(sbp_matrix) {
ilr_sbp_nms <- apply(sbp_matrix, 1, paste, collapse = "")
ilr_sbp_nms <- gsub("-1", "-", ilr_sbp_nms)
ilr_sbp_nms <- gsub("1", "+", ilr_sbp_nms)
ilr_sbp_nms <- gsub("0", ".", ilr_sbp_nms)
return(paste0("ilr(", ilr_sbp_nms, ")"))
}
create_ilr_names(sbp1)
do_closure <- function(x, clo_val = 1) {
return(clo_val * x / sum(x))
}
calc_comp_mean <- function(x, clo_val = 1) {
unclose_mean <- NULL
if (is.null(dim(x))) {
return(x)
} else if (ncol(x) == 1) { # column matrix
return(as.numeric(x))
} else {
unclose_mean <- apply(x, 2, function(x) exp(mean(log(x))))
}
return(do_closure(unclose_mean, clo_val = clo_val))
}
# ---- read ----
bpd_col_spec <-
cols(
Time_Sleep = col_double(),
Time_Sedentary = col_double(),
Time_LPA = col_double(),
Time_MVPA = col_double(),
age = col_double(),
sex = col_character(),
bmi = col_double(),
stress = col_character(),
smoking = col_character(),
education = col_character(),
ses = col_character(),
LBP_sufferer = col_character(),
LBP_frequency_year = col_character(),
LBP_intensity_year = col_double(),
LBP_intensity_month = col_double(),
LBP_intensity_week = col_double()
)
bpd <- read_csv("dat/bpd.csv", col_types = bpd_col_spec)
# head(bpd)
summary(bpd)
# ---- tidy ----
# relevel categories in LBP_frequency_year
y_lab <- "LBP_frequency_year"
sort(unique(bpd[[y_lab]]))
bpd[[y_lab]] <-
if_else(
bpd[[y_lab]] == "more_than90days_but_not_everyday",
"91+_not_evday",
bpd[[y_lab]]
)
# check
table(bpd[[y_lab]], useNA = "ifany")
bpd[[y_lab]] <- factor(bpd[[y_lab]])
levels(bpd[[y_lab]])
lvls_ord <- c(1, 2, 4, 3, 5, 6)
# right order?
# levels(bpd[[y_lab]])[lvls_ord]
bpd[[y_lab]] <- lvls_reorder(bpd[[y_lab]], lvls_ord)
### right order?
levels(bpd[[y_lab]])
with(bpd, table(LBP_frequency_year, LBP_sufferer, useNA = "ifany"))
### comment these lines for sensitivity analysis
if (!is_sensitivity_analysis) {
bpd$age <-
cut(
bpd$age,
breaks = c(17, 44, 64, 100),
labels = c("1_younger", "2_middle", "3_older")
)
print(table(bpd$age))
bpd$bmi <-
cut(
bpd$bmi,
breaks = c(15, 18.5, 25, 70),
right = FALSE,
labels = c("1_underweight", "2_normal", "3_overweight")
)
print(table(bpd$bmi))
}
# ---- impute ----
# Do I have zero values in my composition? (yes in MVPA)
### See: summary(bpd)
# We need to make compositions before we do the lrEM method. The most straightforward way is to create separate datasets and adjust them accordingly.
comp1 <- bpd[, pred_comps]
# How much participants have zero MVPA? 159 participants (6.8% of the sample)
missingSummary(comp1)
sum(rowSums(is.na(comp1) | (comp1 < 0.1)), na.rm = FALSE)
sum(which_0 <- as.logical(rowSums(is.na(comp1) | (comp1 < 0.1))))
# these are 0 vals anywhere in composition (or NA)
bpd[which_0, pred_comps]
# I have zeroes in MVPA - lrEM function will be applied
# ?lrEM
# what is the smallest time-use value above 0? [in minutes]
min(comp1[comp1 > 0])
thresh_detect <- 10 / 1440
# thresh_detect <- 0.01
comp1.a <- comp1 / 1440 # Create % based composition
dl <- c(rep(thresh_detect, times = D)) # threshold limit for the replacement
comp1.zr <- lrEM(comp1.a, label = 0, dl = dl) # conduct the lrEM Zero Replacement
comp1.zr <- as_tibble(comp1.zr * 1440)
# composition is larger than 1440 for those who have imputated MVPA
# (all behaviours will be proportionally downscaled to fit 1440 min when constructing the composition)
# look at imputed values
comp1.zr[which_0, ]
# build dataset that contain imputed values for our 24-h composition
# add new compositions to other noncompositional data
# remove 24-h data from the datase
# bpd <- subset(bpd, select = -c(id, Time_Sleep, Time_Sedentary, Time_LPA, Time_MVPA))
head(bpd[which_0, pred_comps])
bpd <- bpd[, !(colnames(bpd) %in% pred_comps)] # remove ori time-use cols
bpd <- bind_cols(comp1.zr, bpd) # add imputed 24-h data
head(bpd[which_0, pred_comps])
# ---- ilr_create ----
add_ilrs_to_data <- function(dataset, comp_vars = pred_comps, sbp_matrix = sbp1) {
# the time-use composition
comp <- dataset[, comp_vars]
comp <- acomp(comp) # designate it as a compositional variable
# define sequential binary partition (SBP)
psi1 <- gsi.buildilrBase(t(sbp_matrix)) # The orthonormal matrix
# find the mean composition
(m <- mean(comp)) # comp has been designated as acomp, therefore R knows it’s a composition and returns the compositional mean.
# cat(
# "\nThis is the compositional mean [in mins] of the columns (",
# paste(comp_vars, collapse = ", "),
# ")\n\n",
# sep = ""
# )
# print(clo(m, total = 1440)) # to look at the mean in minutes/day.
# cat("\n\n")
# create isometric log ratios (ilr.1) using the above SBP and orthonormal b asis V=psi1. Put ilrs into a data.frame, (X).
ilrs_from_comp <- ilr(comp, V = psi1)
colnames(ilrs_from_comp) <- create_ilr_names(sbp_matrix)
# colnames(ilrs_from_comp) <- paste0("coord", 1:(length(comp_vars) - 1))
dataset$ilr <- ilrs_from_comp
return(dataset)
}
# use function: creates the ilr columns nested in the single column "ilr"
bpd <- add_ilrs_to_data(bpd)
# check
bpd[, c("ilr", pred_comps)]
# also create version of data without the nested ilrs
bpd_clean <- as.data.frame(bpd)
bpd_clean$ilr <- NULL # remove nested cols
bpd_clean <- cbind(bpd_clean, as.data.frame(bpd$ilr))
# ---- explore1 ----
### Missing data summary for LBP suffers
bpd_clean %>%
dplyr::filter(LBP_sufferer == "yes") %>%
md.pattern(., rotate.names = TRUE)
### Missing data summary for _non_ LBP suffers
bpd_clean %>%
dplyr::filter(LBP_sufferer == "no") %>%
md.pattern(., rotate.names = TRUE)
### ===> data doesn't have mistiness for analysis
# ---- explore2 ----
### plot pairwise comparisons of time-use and outcomes
if (FALSE) { # takes 30 sec
suppressWarnings({
bpd_clean %>%
dplyr::select(all_of(pred_comps), all_of(outcs)) %>%
ggpairs(
.,
progress = FALSE,
ggplot2::aes(
colour = LBP_frequency_year,
fill = LBP_frequency_year,
alpha = 0.25
)
) +
theme_bw() +
scale_colour_viridis_d()+
scale_fill_viridis_d()
})
}
### plot pairwise comparisons of _ilrs_ and outcomes
if (TRUE) { # takes 30 sec
suppressWarnings({
bpd_clean %>%
dplyr::select(starts_with("ilr"), all_of(outcs)) %>%
ggpairs(
.,
progress = FALSE,
ggplot2::aes(
colour = LBP_frequency_year,
fill = LBP_frequency_year,
alpha = 0.25
)
) +
theme_bw() +
scale_colour_viridis_d()+
scale_fill_viridis_d()
})
}
# ---- outcome0 ----
bpd <-
bpd %>%
mutate(lbp_occurr = as.integer(LBP_sufferer == "yes"))
(this_outcome <- "lbp_occurr")
# (mod_form_null <-as.formula(paste0(this_outcome, " ~ ", rhs_formula)))
(mod_form_ilrs <-as.formula(paste0(this_outcome, " ~ ", rhs_formula, " + ilr")))
table(bpd[, this_outcome], useNA = "ifany")
# logistic regression model __with__ ilrs
bpd_occurr_ilrs <- glm(mod_form_ilrs, data = bpd, family = binomial())
summary(bpd_occurr_ilrs)
Anova(bpd_occurr_ilrs)
# ---- outcome0_diag ----
### check binned residuals are acceptable
# From the help file:
# Binned residual plots are achieved by “dividing the data into categories
# (bins) based on their fitted values, and then plotting the average residual
# versus the average fitted value for each bin.” (Gelman, Hill 2007: 97).
# If the model were true, one would expect about 95% of the residuals to
# fall inside the error bounds.
bin_res_overall <- binned_residuals(bpd_occurr_ilrs)
bin_res_overall
plot(bin_res_overall)
# ---- outcome0_pred ----
# create dataset for predictions
newdata <-
bpd %>%
dplyr::select(all_of(pred_covs), ilr) %>%
distinct(pick(all_of(pred_covs)), .keep_all = TRUE) %>%
arrange(pick(all_of(pred_covs)))
mean_ilr <- mean(bpd$ilr)
dev_null <- foreach(i = 1:nrow(newdata)) %do% {
newdata$ilr[i, ] <- mean_ilr
}
# make preds and then put in long format for ggplot
predictions_probs <-
cbind(
`P(LBP)` = predict(bpd_occurr_ilrs, newdata, type = "response"),
newdata
) %>%
dplyr::select(-ilr)
# predictions_probs
## model predictions for specific values
pred_plt <-
predictions_probs %>%
dplyr::filter(
# sex == "1_female",
stress == "1_normal",
smoking == "2_nonsmoker",
education == "2_higher",
# ses == "2_middle"
) %>%
ggplot(., aes(age, `P(LBP)`, group = bmi)) +
geom_line(aes(colour = bmi), linewidth = 1) +
geom_point(aes(colour = bmi), size = 2) +
facet_grid(sex~ ses, labeller = label_both) +
labs(x = "age", y = "estimated P(lower back pain sufferer)") +
theme_bw() +
theme(axis.text.x = element_text(angle = 45))
if (is_sensitivity_analysis) {
pred_plt <- pred_plt + scale_colour_viridis_b(option = "H")
} else {
pred_plt <- pred_plt + scale_color_manual(values = c("orange2", "turquoise", "purple"))
}
pred_plt
# create a RHS of regression equation dataset for time-reallocation
predict_basis <-
bpd %>%
dplyr::select(all_of(pred_covs), all_of(pred_comps)) %>%
dplyr::filter(
# age == "2_middle",
sex == "1_female",
stress == "1_normal",
smoking == "2_nonsmoker",
education == "2_higher",
ses == "2_middle",
bmi == "2_normal"
)
if (is_sensitivity_analysis) {
# continuous scenario
predict_basis$age <- mean(predict_basis$age)
} else { # std analysis
predict_basis <-
predict_basis %>% dplyr::filter(age == "2_middle")
}
(predict_basis <-
predict_basis %>%
distinct(across(all_of(pred_covs)), .keep_all = TRUE) %>%
as.data.frame())
# compositional mean: geometric mean to closure
# (comp_mean <- mean(acomp(bpd[, pred_comps])))
(comp_mean <- calc_comp_mean(bpd[, pred_comps], clo_val = 1440))
predict_basis0 <- predict_basis
predict_basis0[, pred_comps] <- comp_mean
predict_basis0
# +15 minutes to Time_MVPA and -15 minutes from Time_Sedentary
comp_mean_changed <- comp_mean
comp_mean_changed["Time_MVPA"] <- comp_mean_changed["Time_MVPA"] + 15
comp_mean_changed["Time_Sedentary"] <- comp_mean_changed["Time_Sedentary"] - 15
# check
comp_mean_changed - comp_mean
predict_basis1 <- predict_basis
predict_basis1[, pred_comps] <- comp_mean_changed
pred_df <- rbind(predict_basis0, predict_basis1)
pred_df <- add_ilrs_to_data(pred_df, comp_vars = pred_comps, sbp_matrix = sbp1)
pred_df
predict(bpd_occurr_ilrs, pred_df, type = "link")
# ratio of odds ratios
exp(diff(predict(bpd_occurr_ilrs, pred_df, type = "link")))
get_pred_diff <- function(mod, new_dat) {
log_odds_pred <- predict(mod, new_dat, type = "link")
odds_ratio_ratio <- exp(log_odds_pred[2] - log_odds_pred[1])
return(odds_ratio_ratio)
}
(est_v1 <- get_pred_diff(bpd_occurr_ilrs, pred_df))
fit_mod_boot <- function(data, i, pred_dat) {
this_dat <- data[i, ]
this_logis <- glm(mod_form_ilrs, data = this_dat, family = binomial())
est <- get_pred_diff(this_logis, new_dat = pred_dat)
return(est)
}
### CI method #1 (bootstrapping):
alpha <- 0.05
(ci_v1 <-
c(
est = est_v1,
quantile(
boot(bpd, fit_mod_boot, R = 100, pred_dat = pred_df)$t,
c(alpha / 2, 1 - alpha / 2)
)))
### alternative CI method #2 (Wald approximation - re-transformed):
pred_df[, "ilr"]
diff(pred_df[, "ilr"])
x_0_red <- matrix(as.numeric(diff(pred_df[, "ilr"])), nrow = 1)
x_0_red
betas <- coef(bpd_occurr_ilrs)
nms_kp <- grepl("^ilr", names(betas))
betas_red <- as.matrix(betas[nms_kp])
Sigma <- stats::vcov(bpd_occurr_ilrs)
nms_kp <- grepl("^ilr", colnames(Sigma))
sigma_red <- Sigma[nms_kp, nms_kp]
sigma_red
est_red <- x_0_red %*% betas_red
se_red <- sqrt(x_0_red %*% sigma_red %*% t(x_0_red))
z_star <- qnorm(0.975)
(ci_v2 <-
exp(c(
est = est_red,
lo = est_red - z_star * se_red,
hi = est_red + z_star * se_red
)))
### alternative CI method #3 (delta method)
# (first order approximation, although still linear combin of param ests):
approx_ci <-
deltaMethod(
bpd_occurr_ilrs,
"-0.2418864 * `ilrilr(++--)` + 0.02454151 * `ilrilr(+-..)` + -0.3175375 * `ilrilr(..+-)`"
)
(ci_v3 <-
exp(c(
est = approx_ci[["Estimate"]],
lo = approx_ci[["2.5 %"]],
hi = approx_ci[["97.5 %"]]
)))
### compare CIs
kable(rbind(ci_v1, ci_v2, ci_v3))
do_multi_realloc <- function(mod, basis_data, timeusenames, time_changes, sbp_matrix = sbp1) {
x0 <- basis_data
plot_dat <-
foreach(i = 1:length(timeusenames), .combine = bind_rows) %do% {
print(paste("i: ", i))
foreach(j = 1:length(timeusenames), .combine = bind_rows) %do% {
print(paste(" j: ", j))
foreach(d = 1:length(time_changes), .combine = bind_rows) %do% {
print(paste(" d: ", d))
timeuse_to <- timeusenames[i]
timeuse_from <- timeusenames[j]
change_time <- time_changes[d]
proposed_change_1 <- x0[timeuse_to] + change_time
proposed_change_2 <- x0[timeuse_from] - change_time
if (timeuse_to == timeuse_from) {
NULL # reallocation exceeds 0 or max time
} else if ((proposed_change_1 < 0) | (proposed_change_1 > 1440)) {
NULL # reallocation exceeds 0 or max time
} else if ((proposed_change_2 < 0) | (proposed_change_2 > 1440)) {
NULL # reallocation exceeds 0 or max time
} else {
x1 <- x0
x1[timeuse_to] <- x1[timeuse_to] + change_time
x1[timeuse_from] <- x1[timeuse_from] - change_time
pred_df <- rbind(x0, x1)
pred_df <- add_ilrs_to_data(pred_df, comp_vars = timeusenames, sbp_matrix = sbp_matrix)
ratio_of_odds_ratios <- get_pred_diff(mod, pred_df)
bootstrapped_ests <- boot(bpd, fit_mod_boot, R = 1000, pred_dat = pred_df)$t
ci_est <- quantile(as.numeric(bootstrapped_ests), c(alpha / 2, 1 - alpha / 2))
tibble(
to = timeuse_to,
from = timeuse_from,
change_time = change_time,
ratio_of_odds_ratios = ratio_of_odds_ratios,
ci_lo = ci_est[1],
ci_hi = ci_est[2]
)
}
}
}
}
plot_dat$to <- factor(plot_dat$to, levels = timeusenames)
plot_dat$from <- factor(plot_dat$from, levels = timeusenames)
return(plot_dat)
}
# takes ~25 min (single core)
### Uncomment to generate bootstrapping
# tic()
# set.seed(1234)
# realloc_plot_data <-
# do_multi_realloc(
# bpd_occurr_ilrs,
# predict_basis0,
# pred_comps,
# seq(-30, 30, by = 10)
# )
# saveRDS(realloc_plot_data, file = "res/logistic_realloc_boot_res.rda")
# toc()
realloc_plot_data <- readRDS(file = "res/logistic_realloc_boot_res.rda")
levels(realloc_plot_data$to) <- paste0(levels(realloc_plot_data$to), "+Delta")
levels(realloc_plot_data$from) <- paste0(levels(realloc_plot_data$from), "-Delta")
ggplot(realloc_plot_data) +
geom_vline(xintercept = 0, col = "grey60") +
geom_hline(yintercept = 1, col = "grey60") +
geom_ribbon(aes(x = change_time, ymin = ci_lo, ymax = ci_hi, fill = to), alpha = 0.3) +
geom_line(aes(x = change_time , y = ratio_of_odds_ratios, col = to)) +
geom_point(aes(x = change_time , y = ratio_of_odds_ratios, col = to), size = 1) +
facet_grid(from ~ to, labeller = label_parsed) +
theme_bw() +
scale_colour_manual(values = c("darkorange", "purple", "cyan4", "dodgerblue")) +
scale_fill_manual(values = c("darkorange", "purple", "cyan4", "dodgerblue")) +
labs(
x = paste0("Change/delta in composition (mins)"),
y = paste0("Ratio of odds-ratios (after reallocation:before reallocation)")
) +
theme(legend.position = "none")
ggsave(
filename = "fig/lbp_occur_logistic_odds.png",
dpi = 600, # print quality
width = 10,
height = 10
)
# ---- update_data ----
bpd_yes <- bpd %>% dplyr::filter(LBP_sufferer == "yes")
nrow(bpd)
nrow(bpd_yes)
bpd_clean_yes <- bpd_clean %>% dplyr::filter(LBP_sufferer == "yes")
# ---- outcome1 ----
(this_outcome <- outcs[1])
# (mod_form_null <-as.formula(paste0(this_outcome, " ~ ", rhs_formula)))
(mod_form_ilrs <-as.formula(paste0(this_outcome, " ~ ", rhs_formula, " + ilr")))
table(bpd_yes[, this_outcome], useNA = "ifany")
bpd_yes[[this_outcome]] <- fct_drop(bpd_yes[[this_outcome]])
table(bpd_yes[, this_outcome], useNA = "ifany")
## model without ilrs
# bpd_ordinal_null <- polr(mod_form_null, data = bpd, Hess = TRUE, method = "logistic")
# summary(bpd_ordinal_null)
## model __with__ ilrs
bpd_ordinal_ilrs <- polr(mod_form_ilrs, data = bpd_yes, Hess = TRUE, method = "logistic")
summary(bpd_ordinal_ilrs)
Anova(bpd_ordinal_ilrs)
# pr <- profile(bpd_ordinal_ilrs)
# confint(pr)
# plot(pr)
# pairs(pr)
est_ci_df <- cbind(est = coef(bpd_ordinal_ilrs), confint(bpd_ordinal_ilrs)) # profiled CIs
kable(est_ci_df, digits = 3) # these are the log-odds scale estimates (and CI)
kable(exp(est_ci_df), digits = 3) # these are the odds ratios (and approx CIs)
# ---- outcome1_diag ----
# deviance test
g2 <- deviance(bpd_ordinal_ilrs)
df <- df.residual(bpd_ordinal_ilrs)
1 - pchisq(g2, df)
with(bpd_yes,
table(
LBP_frequency_year,
as.numeric(LBP_frequency_year),
useNA = "ifany"
)
)
## checking parallel slopes assumptions can be done by fitting successive logistic regressions
## while creating a binary outcome using different thresholds of the ordinal outcome
### (note the rhs/linear predictor is negative so coefs should be approx same
### as main model except negative)
# e.g. this is a single logistic regression
coef(glm(
I(as.numeric(LBP_frequency_year) <= 1) ~
age + sex + bmi + stress + smoking + education + ses + ilr,
family = "binomial",
data = bpd_yes
))
# this is running multiple logistic regressions
## we want to see the coefficients to be roughly the same (intercepts and negative coefs - see above)
### note that the below shows there may be reason to include an age variable that has
### non-constant coefficient for each level of the outcome (or subgroup analyses for each age cohort)
### we can see this because the age coefs increase/decrease monotonically
foreach(i = 1:(length(levels(bpd_yes$LBP_frequency_year)) - 1), .combine = cbind) %do% {
log_coefs <-
coef(glm(
I(as.numeric(LBP_frequency_year) <= i) ~
age + sex + bmi + stress + smoking + education + ses + ilr,
family = "binomial",
data = bpd_yes
))
log_coefs <- as.data.frame(log_coefs)
colnames(log_coefs) <- paste0("logit(P(Y<=", i, "))")
log_coefs
} %>%
kable(., digits = 2)
# ---- outcome1_pred_a ----
# create dataset for predictions
newdata <-
bpd_yes %>%
dplyr::select(all_of(pred_covs), ilr) %>%
distinct(pick(all_of(pred_covs)), .keep_all = TRUE) %>%
arrange(pick(all_of(pred_covs)))
mean_ilr <- mean(bpd_yes$ilr)
dev_null <- foreach(i = 1:nrow(newdata)) %do% {
newdata$ilr[i, ] <- mean_ilr
}
# make preds and then put in long format for ggplot
predictions_probs <-
cbind(
predict(bpd_ordinal_ilrs, newdata, type = "probs"),
newdata
) %>%
dplyr::select(-ilr) %>%
pivot_longer(
cols = -all_of(pred_covs),
names_to = "outcome",
values_to = "P(outc)"
)
predictions_probs
## model predictions for specific values
pred_plt <-
predictions_probs %>%
dplyr::filter(
# sex == "1_female",
stress == "1_normal",
smoking == "2_nonsmoker",
education == "2_higher",
# ses == "2_middle"
) %>%
ggplot(., aes(outcome, `P(outc)`))
if (is_sensitivity_analysis) {
pred_plt <-
pred_plt +
geom_line(aes(colour = age, group = age), linewidth = 1) +
geom_point(aes(colour = age), size = 2) +
facet_grid(sex ~ ses, labeller = label_both) +
labs(x = "Outcome: back pain freq", y = "estimated P(outcome)") +
scale_colour_viridis_b()
} else {
pred_plt <-
pred_plt +
geom_line(aes(colour = age, group = age), linewidth = 1) +
geom_point(aes(colour = age), size = 2) +
facet_grid(sex * bmi ~ ses, labeller = label_both) +
labs(x = "Outcome: back pain freq", y = "estimated P(outcome)") +
scale_colour_viridis_d()
}
pred_plt + theme_bw()
# ---- outcome1_pred_b ----
# create a RHS of regression equation dataset for time-reallocation
predict_basis <-
bpd_yes %>%
dplyr::select(all_of(pred_covs), all_of(pred_comps)) %>%
dplyr::filter(
# age == "2_middle",
sex == "1_female",
stress == "1_normal",
smoking == "2_nonsmoker",
education == "2_higher",
ses == "2_middle",
bmi == "2_normal"
)
if (is_sensitivity_analysis) {
# continuous scenario
predict_basis$age <- mean(predict_basis$age)
} else { # std analysis
predict_basis <-
predict_basis %>% dplyr::filter(age == "2_middle")
}
(predict_basis <-
predict_basis %>%
distinct(across(all_of(pred_covs)), .keep_all = TRUE) %>%
as.data.frame())
# compositional mean: geometric mean to closure
# (comp_mean <- mean(acomp(bpd_yes[, pred_comps])))
(comp_mean <- calc_comp_mean(bpd_yes[, pred_comps], clo_val = 1440))
predict_basis0 <- predict_basis
predict_basis0[, pred_comps] <- comp_mean
predict_basis0
# +15 minutes to Time_MVPA and -15 minutes from Time_Sedentary
comp_mean_changed <- comp_mean
comp_mean_changed["Time_MVPA"] <- comp_mean_changed["Time_MVPA"] + 15
comp_mean_changed["Time_Sedentary"] <- comp_mean_changed["Time_Sedentary"] - 15
# check
comp_mean_changed - comp_mean
predict_basis1 <- predict_basis
predict_basis1[, pred_comps] <- comp_mean_changed
pred_df <- rbind(predict_basis0, predict_basis1)
pred_df <- add_ilrs_to_data(pred_df, comp_vars = pred_comps, sbp_matrix = sbp1)
pred_df <- pred_df[, !(colnames(pred_df) %in% pred_comps)] # get rid of compositions
pred_df
# model.matrix(formula(bpd_ordinal_ilrs), data = cbind(LBP_frequency_year = 0, pred_df))
df <- bpd_yes[, attr(formula(bpd_ordinal_ilrs), "term.labels")]
# this is a list of levels for each factor in the original df (after applying factor funciton)
xlevs <- lapply(df[,sapply(df, is.character), drop = F], function(j) {
levels(factor(j))
})
# calling "xlev = " builds out a model.matrix with identical levels as the original df
mm_new <- model.matrix( ~ ., data = pred_df, xlev = xlevs)
colnames(mm_new)
mm_new <- mm_new[, -1] # remove intercept
colnames(mm_new)[grepl("^ilr", colnames(mm_new))] <- paste0("ilr", create_ilr_names(sbp1))
# colnames(mm_new)
# don't need intercept # c("(Intercept)" = 1, coef(bpd_ordinal_ilrs))
betas <- as.matrix(coef(bpd_ordinal_ilrs)) # should be col matrix
# rownames(betas)
if (!all(colnames(mm_new) == rownames(betas))) {
stop("design and parameter est matrices non-conform")
}
# note as linear predictor is taken from the K intercepts the ratio of odds ratios is flipped
# i.e. after:before of odds is calculated as exp(before_log_odds / after_log_odds)
preds <- mm_new %*% betas
exp(preds[1] - preds[2])
# check manual calcs agree with model
mm_old <- model.matrix( ~ ., data = df, xlev = xlevs)
mm_old <- mm_old[, -1] # remove intercept
# colnames(mm_old)
# model and manual calcs agree?
# note that bpd_ordinal_ilrs$lp are the eta/linear predictor that is taken
# away from the xi_k intercept
all(abs(as.numeric(mm_old %*% betas) - bpd_ordinal_ilrs$lp) < 1e-9)
# bpd_ordinal_ilrs$lp # linear predictor
get_pred_diff <- function(mod, new_dat) {
betas_ <- as.matrix(coef(mod))
if (!all(colnames(new_dat) == rownames(betas_))) {
print(paste(paste(colnames(new_dat), collapse = "|"), "vs", paste(rownames(betas_), collapse = "|")))
stop("design and parameter est matrices non-conform")
}
log_odds_pred <- as.numeric(new_dat %*% betas_)
# note reversal of order (see above)
odds_ratio_ratio <- exp(log_odds_pred[1] - log_odds_pred[2])
return(odds_ratio_ratio)
}
(est_v1 <- get_pred_diff(bpd_ordinal_ilrs, mm_new))