/
externVar.R
2028 lines (1776 loc) · 84.5 KB
/
externVar.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
#' Estimation of secondary regression models after the estimation of a primary latent class model
#'
#' This function fits regression models to relate a latent class structure (stemmed
#' from a latent class model estimated within \code{lcmm} package) with either an external
#' outcome or external class predictors.
#' Two inference techniques are implemented to account for the classification error:
#'
#' - a 2-stage estimation of the joint likelihood of the primary latent class model
#' and the secondary/ external regression;
#'
#' - a regression between the posterior latent class assignment and the external variable
#' which internally corrects for the assignment misclassification.
#'
#' It returns an object from one of the \code{lcmm} package classes.
#'
#' A. DATA STRUCTURE
#'
#' The \code{data} argument must follow specific structure for individual variables,
#' i.e. variables with a unique constant value for each subject. For an individual variable
#' given as external outcome, data value must be present only once per subject,
#' independently of any time variable used in the primary latent class.
#' For an individual variable given as external class predictor,
#' data values must be given for every row of every individual (as usual)
#'
#' B. VARIANCE ESTIMATION
#'
#' Not taking into account first stage variance with specifing \code{"none"} may lead to
#' underestimation of the final variance. When possible, Method \code{"Hessian"}
#' which relies on the combination of Hessians from the primary and secondary
#' model is recommended. However, it may become numerically intensive in the event
#' of very high number of parameters in the primary latent class model. As an
#' alternative, especially in situations with a complex primary model but rather
#' parcimonious secondary model, method \code{"paramBoot"} which implements a
#' parametric bootstrap can be used.
#'
#' @param model an object inheriting from class \code{hlme}, \code{lcmm},
#' \code{Jointlcmm}, \code{multlcmm} or \code{mpjlcmm} giving the primary latent
#' class model.
#' @param fixed optional two sided linear formula object for specifying the
#' fixed-effects in the secondary model with an external outcome variable.
#' The response outcome is on the left of \code{~} and the covariates are separated
#' by \code{+} on the right of the \code{~}. By default, an intercept is included.
#' @param mixture optional one-sided formula object for the class-specific fixed effects
#' in the model for the external outcome. Among the list of covariates included in fixed,
#' the covariates with class-specific regression parameters are entered in
#' mixture separated by \code{+}. By default, an intercept is included.
#' If no intercept, \code{-1} should be the first term included.
#' @param random optional one-sided linear formula object for specifying the
#' random-effects on external outcome in the secondary model, if appropriate.
#' By default, no random effect is included.
#' @param subject name of the covariate representing the grouping structure.
#' Even in the absence of a hierarchical structure.
#' @param classmb optional one-sided formula specifying the external predictors of
#' latent class membership to be modelled in the secondary class-membership multinomial
#' logistic model. Covariates are separated by \code{+} on the right of the \code{~}.
#' @param survival optional two-sided formula specifying the external survival part
#' of the model.
#' @param hazard optional family of hazard function assumed for the survival model
#' (Weibull, piecewise or splines)
#' @param hazardtype optional indicator for the type of baseline risk function
#' (Specific, PH or Common)
#' @param hazardnodes optional vector containing interior nodes if \code{splines} or
#' \code{piecewise} is specified for the baseline hazard function in \code{hazard}
#' @param TimeDepVar optional vector specifying the name of the time-depending covariate
#' in the survival model
#' @param logscale optional boolean indicating whether an exponential (logscale=TRUE) or
#' a square (logscale=FALSE -by default) transformation is used to
#' ensure positivity of parameters in the baseline risk functions
#' @param idiag if appropriate, optional logical for the structure of the variance-covariance
#' matrix of the random-effects in the secondary model.
#' If \code{FALSE}, a non structured matrix of
#' variance-covariance is considered (by default). If \code{TRUE} a diagonal
#' matrix of variance-covariance is considered.
#' @param nwg if appropriate, optional logical indicating if the variance-covariance of the
#' random-effects in the secondary model is class-specific. If \code{FALSE} the
#' variance-covariance matrix is common over latent classes (by default). If \code{TRUE} a
#' class-specific proportional parameter multiplies the variance-covariance
#' matrix in each class (the proportional parameter in the last latent class
#' equals 1 to ensure identifiability).
#' @param randomY optional logical for including an outcome-specific random intercept.
#' If FALSE no outcome-specific random intercept is added (default). If TRUE independent
#' outcome-specific random intercept with parameterized variance are included
#' @param link optional family of parameterized link functions for the external outcome
#' if appropriate. Defaults to NULL, corresponding to continuous Gaussian distribution
#' (hlme function).
#' @param intnodes optional vector of interior nodes. This argument is only
#' required for a I-splines link function with nodes entered manually.
#' @param epsY optional definite positive real used to rescale the marker in (0,1)
#' when the beta link function is used. By default, epsY=0.5.
#' @param cor optional indicator for inclusion of an auto correlated Gaussian process
#' in the latent process linear (latent process) mixed model. Option "BM" indicates
#' a brownian motion with parameterized variance. Option "AR" specifies an
#' autoregressive process of order 1 with parameterized variance and correlation
#' intensity. Each option should be followed by the time variable in brackets as
#' code{cor=BM(time)}. By default, no autocorrelated Gaussian process is added.
#' @param nsim number of points to be used in the estimated link function. By default,
#' nsom=100.
#' @param range optional vector indicating the range of the outcomes (that is the
#' minimum and maximum). By default, the range is defined according to the minimum
#' and maximum observed values of the outcome. The option should be used
#' only for Beta and Splines transformations.
#' @param data Data frame containing the variables named in
#' \code{fixed}, \code{mixture}, \code{random}, \code{classmb} and \code{subject},
#' for both the current function arguments and the primary model arguments
#' Check \code{details} to get information on the data structure, especially with
#' external outcomes.
#' @param longitudinal only with \code{mpjlcmm} primary models and "twoStageJoint"
#' method: mandatory list containing the longitudinal submodels used in the primary
#' latent class model.
#' @param method character indicating the inference technique to be used:
#' \code{"twoStageJoint"} corresponds to 2-stage estimation. \code{"conditional"}
#' corresponds to the method based on the distribution of Y conditionally to the
#' true latent class membership.
#' @param varest optional character indicating the method to be used to compute the
#' variance of the regression estimates. \code{"none"} does not account for the
#' uncertainty in the primary latent class model, \code{"paramBoot"} computes the
#' total variance using a parametric bootstrap technique, \code{"Hessian"} computes
#' the total Hessian of the joint likelihood (implemented for \code{"twoStageJoint"}
#' method only). Default to \code{"Hessian"} for \code{"twoStageJoint"} method and
#' \code{"paramBoot"} for \code{"conditional"} method.
#' @param M option integer indicating the number of draws for the parametric boostrap
#' when \code{varest="paramBoot"}. Default to 200.
#' @param B optional vector of initial parameter values for the secondary model.
#' If external outcome, the vector has the same structure as a latent class model
#' estimated in the other functions of \code{lcmm} package for the same type of
#' outcome. If external class predictors (of size p), the vector is of length
#' (ng-1)*(1+p). If \code{B=NULL} (by default), internal initial values are selected.
#' @param convB optional threshold for the convergence criterion based on the
#' parameter stability. By default, convB=0.0001.
#' @param convL optional threshold for the convergence criterion based on the
#' log-likelihood stability. By default, convL=0.0001.
#' @param convG optional threshold for the convergence criterion based on the
#' derivatives. By default, convG=0.0001.
#' @param maxiter optional maximum number of iterations for the secondary model
#' estimation using Marquardt iterative algorithm. Defaults to 100
#' @param posfix optional vector specifying indices in parameter vector B the
#' secondary model that should not be estimated. Default to NULL, all the
#' parameters of the secondary regression are estimated.
#' @param partialH optional logical for Piecewise and Splines baseline risk functions and
#' Splines link functions only. Indicates whether the parameters of the baseline risk or
#' link functions can be dropped from the Hessian matrix to define convergence criteria
#' (can solve non convergence due to estimates at the boundary of the parameter space - usually 0).
#' @param verbose logical indicating whether information about computation should be
#' reported. Default to FALSE.
#' @param nproc the number cores for parallel computation. Default to 1 (sequential mode).
#' @return an object of class \code{externVar} and
#' \code{externSurv} for external survival outcomes,
#' \code{externX} for external class predictors, and
#' \code{hlme}, \code{lcmm}, or \code{multlcmm} for external longitudinal or cross-sectional outcomes.
#' @author Maris Dussartre, Cecile Proust-Lima and Viviane Philipps
#'
#'
#' @examples
#'
#' \dontrun{
#'
#'
#' ###### Estimation of the primary latent class model ######
#'
#' set.seed(1234)
#' PrimMod <- hlme(Ydep1~Time,random=~Time,subject='ID',ng=1,data=data_lcmm)
#' PrimMod2 <- hlme(Ydep1~Time,mixture=~Time,random=~Time,subject='ID',
#' ng=2,data=data_lcmm,B=random(PrimMod))
#'
#' ###### Example 1: Relationship between a latent class structure and #
#' # external class predictors ######
#'
#' # estimation of the secondary multinomial logistic model with total variance
#' # computed with the Hessian
#'
#' XextHess <- externVar(PrimMod2,
#' classmb = ~X1 + X2 + X3 + X4,
#' subject = "ID",
#' data = data_lcmm,
#' method = "twoStageJoint")
#' summary(XextHess)
#'
#' # estimation of a secondary multinomial logistic model with total variance
#' # computed with parametric Bootstrap (much longer). When using the bootstrap
#' # estimator, we recommend running first the analysis with option varest = "none"
#' # which is faster but which underestimates the variance. And then use these values
#' # as initial values when running the model with varest = "paramBoot" to obtain
#' # a valid variance of the parameters.
#'
#' XextNone <- externVar(PrimMod2,
#' classmb = ~X1 + X2 + X3 + X4,
#' subject = "ID",
#' data = data_lcmm,
#' varest = "none",
#' method = "twoStageJoint")
#'
#' XextBoot <- externVar(PrimMod2,
#' classmb = ~X1 + X2 + X3 + X4,
#' subject = "ID",
#' data = data_lcmm,
#' varest = "paramBoot",
#' method = "twoStageJoint",
#' B = XextNone$best)
#' summary(XextBoot)
#'
#'
#' ###### Example 2: Relationship between a latent class structure and #
#' # external outcome (repeatedly measured over time) ######
#'
#' # estimation of the secondary linear mixed model with total variance
#' # computed with the Hessian
#'
#' YextHess = externVar(PrimMod2, #primary model
#' fixed = Ydep2 ~ Time*X1, #secondary model
#' random = ~Time, #secondary model
#' mixture = ~Time, #secondary model
#' subject="ID",
#' data=data_lcmm,
#' method = "twoStageJoint")
#'
#'
#' # estimation of a secondary linear mixed model with total variance
#' # computed with parametric Bootstrap (much longer). When using the bootstrap
#' # estimator, we recommend running first the analysis with option varest = "none"
#' # which is faster but which underestimates the variance. And then use these values
#' # as initial values when running the model with varest = "paramBoot" to obtain
#' # a valid variance of the parameters.
#'
#' YextNone = externVar(PrimMod2, #primary model
#' fixed = Ydep2 ~ Time*X1, #secondary model
#' random = ~Time, #secondary model
#' mixture = ~Time, #secondary model
#' subject="ID",
#' data=data_lcmm,
#' varest = "none",
#' method = "twoStageJoint")
#'
#' YextBoot = externVar(PrimMod2, #primary model
#' fixed = Ydep2 ~ Time*X1, #secondary model
#' random = ~Time, #secondary model
#' mixture = ~Time, #secondary model
#' subject="ID",
#' data=data_lcmm,
#' method = "twoStageJoint",
#' B = YextNone$best,
#' varest= "paramBoot")
#'
#' summary(YextBoot)
#'
#'
#' ###### Example 3: Relationship between a latent class structure and #
#' # external outcome (survival) ######
#'
#' # estimation of the secondary survival model with total variance
#' # computed with the Hessian
#'
#' YextHess = externVar(PrimMod2, #primary model
#' survival = Surv(Tevent,Event)~ X1+mixture(X2), #secondary model
#' hazard="3-quant-splines", #secondary model
#' hazardtype="PH", #secondary model
#' subject="ID",
#' data=data_lcmm,
#' method = "twoStageJoint")
#' summary(YextHess)
#'
#'
#' # estimation of a secondary survival model with total variance
#' # computed with parametric Bootstrap (much longer). When using the bootstrap
#' # estimator, we recommend running first the analysis with option varest = "none"
#' # which is faster but which underestimates the variance. And then use these values
#' # as initial values when running the model with varest = "paramBoot" to obtain
#' # a valid variance of the parameters.
#'
#' YextNone = externVar(PrimMod2, #primary model
#' survival = Surv(Tevent,Event)~ X1+mixture(X2), #secondary model
#' hazard="3-quant-splines", #secondary model
#' hazardtype="PH", #secondary model
#' subject="ID",
#' data=data_lcmm,
#' varest = "none",
#' method = "twoStageJoint")
#'
#' YextBoot = externVar(PrimMod2, #primary model
#' survival = Surv(Tevent,Event)~ X1+mixture(X2), #secondary model
#' hazard="3-quant-splines", #secondary model
#' hazardtype="PH", #secondary model
#' subject="ID",
#' data=data_lcmm,
#' method = "twoStageJoint",
#' B = YextNone$best,
#' varest= "paramBoot")
#'
#' summary(YextBoot)
#'
#' }
#'
#'
#'
#'
#' @export
#'
#'
#'
externVar = function(model,
fixed,
mixture,
random,
subject,
classmb,
survival,
hazard = "Weibull",
hazardtype = "Specific",
hazardnodes = NULL,
TimeDepVar = NULL,
logscale = FALSE,
idiag = FALSE,
nwg = FALSE,
randomY = NULL,
link = NULL,
intnodes = NULL,
epsY = NULL,
cor = NULL,
nsim = NULL,
range = NULL,
data,
longitudinal,
method,
varest,
M = 200,
B,
convB = 0.0001,
convL = 0.0001,
convG = 0.0001,
maxiter = 100,
posfix,
partialH = FALSE,
verbose = FALSE,
nproc = 1){
ptm <- proc.time()
if(missing(model)) stop("model argument must be given")
if(!inherits(model, c("hlme", "lcmm", "multlcmm", "Jointlcmm", "mpjlcmm"))) stop('primary model class must be either "hlme", "lcmm", "multlcmm", "Jointlcmm" or "mpjlcmm"')
if(model$conv == 2) warning("primary model did not fully converge")
if(sum(c(!missing(fixed), !missing(classmb), !missing(survival))) != 1) stop("One and only one in survival, fixed or classmb must be given")
if(missing(method) | !method %in% c("twoStageJoint", "conditional")) stop('Method must be either "twoStageJoint" or "conditional"')
if(model$ng == 1) stop("Primary model does not have latent class structure (ng=1)")
if(method == "twoStageJoint" & missing(varest)) varest = "Hessian"
if(method == "conditional" & missing(varest)) varest = "paramBoot"
if(!varest %in% c("none", "paramBoot", "Hessian")) stop('Variance estimation method "varest" must be either "none", "paramBoot" or "Hessian"')
if(!is.null(link) & missing(fixed)) stop("The argument link is not to be used with external class predictor")
if(missing(posfix)) posfix = c()
cl = match.call()
##Informations about primary model
argumentsIn = as.list(model$call)
funIn = as.character(argumentsIn[[1]])
if(funIn == "jlcmm") funIn <- "Jointlcmm"
if(funIn == "mlcmm") funIn <- "multlcmm"
argumentsIn[[1]] = NULL
ng = model$ng
nIn = length(model$best)
if(is.null(argumentsIn[["classmb"]])){
oldclassmb = ~ 1
} else {
oldclassmb = formula(argumentsIn[["classmb"]])
}
if(!missing(classmb) & oldclassmb != ~1) stop("Primary model already has class predictor")
##number of MB parameters in primary model
nInMB = ncol(model.matrix(oldclassmb, data))*(ng-1)
##Get subject
if(missing(subject)){
if (model$call$subject %in% colnames(data)){
subject = model$call$subject
} else {
stop("The argument subject must be specified if different from the subject argument used in the primary model")
}
}
##Get longitudinal
if(funIn == "mpjlcmm"){
if(missing(longitudinal)) stop("The argument longitudinal is mandatory with a mpjlcmm primary model")
longCall = substitute(longitudinal)
K = length(longitudinal)
for(k in 1:K){
cl_long = as.list(longitudinal[[k]]$call)
if(inherits(longitudinal[[k]], "lcmm")) cl_long[["computeDiscrete"]] = FALSE
longitudinal[[k]]$call = as.call(cl_long)
assign(as.character(longCall[[k+1]]), longitudinal[[k]])
}
}
##nVCIn
if(funIn == "mpjlcmm"){
nVCIn = model$Nprm[3+2*model$K+(1:model$K)]
iVCIn = c()
prev = 0
for(k in 1:model$K){
iVCIn = c(iVCIn, sum(model$Nprm[c(1:3, 3:4*model$K-model$K+k-1)])+prev+1:nVCIn[k])
prev = prev+model$npmK[k]
}
} else if(funIn == "Jointlcmm"){
nVCIn = model$N[5]
iVCIn = sum(model$N[1:4]) + 1:nVCIn
} else if(funIn == "multlcmm"){
nVCIn = model$N[4]
iVCIn = sum(model$N[3]) + 1:nVCIn
} else {
nVCIn = model$N[3]
iVCIn = sum(model$N[1:2]) + 1:nVCIn
}
##pprob with new data
argumentsInEdit = argumentsIn
argumentsInEdit[["data"]] = data
argumentsInEdit[["maxiter"]] = 0
argumentsInEdit[["B"]] = model$best
argumentsInEdit[["verbose"]] = FALSE
modelEdit = do.call(funIn, argumentsInEdit)
pprob = modelEdit$pprob
arguments = list()
##Finding out the number of parameters is needed for all survival external outcome
if(!missing(survival)){
##Informations about secondary outcome model
##number of survival parameters to estimate
##number of events
surv <- cl$survival[[2]]
if(length(surv)==3) #censure droite sans troncature gauche
{
idtrunc <- 0
nom.Tevent <- as.character(surv[2])
nom.Event <- as.character(surv[3])
nom.Tentry <- NULL #si pas de troncature, Tentry=0
noms.surv <- c(nom.Tevent,nom.Event)
}
if(length(surv)==4) #censure droite et troncature
{
idtrunc <- 1
nom.Tentry <- as.character(surv[2])
nom.Tevent <- as.character(surv[3])
nom.Event <- as.character(surv[4])
noms.surv <- c(nom.Tentry,nom.Tevent,nom.Event)
}
Tevent <- getElement(object=data,name=nom.Tevent)
Event <- getElement(object=data,name=nom.Event)
nbevt <- length(attr(do.call("Surv",list(time=Tevent,event=Event,type="mstate")),"states"))
if(nbevt<1) nbevt <- 1
##get number of parameters for baseline functions
hazard <- rep(hazard,length.out=nbevt)
hazardtype <- rep(hazardtype,length.out=nbevt)
if(any(hazard %in% c("splines","Splines")))
{
hazard[which(hazard %in% c("splines","Splines"))] <- "5-quant-splines"
}
if(any(hazard %in% c("piecewise","Piecewise")))
{
hazard[which(hazard %in% c("piecewise","Piecewise"))] <- "5-quant-piecewise"
}
hazWhat = hazard
##when not weibull, keep only the last word of hazard
hazWhat[hazard != 'Weibull'] = sapply(strsplit(hazard[hazard != 'Weibull'], "-"), `[`, 3)
hazN = rep(2, nbevt)
hazN[hazard != 'Weibull'] = sapply(strsplit(hazard[hazard != 'Weibull'], "-"), `[`, 1)
hazN = as.integer(hazN)
hazN = hazN +
(hazWhat == "Weibull")*0 +
(hazWhat == "piecewise")*(-1) +
(hazWhat == "splines")*(2)
hazN = hazN + hazN *
(hazardtype == "Specific")*(ng-1)
##we extract the number of base function parameter with constraints (ie, not PH parameters)
nSurvConstraint = hazN
hazN = hazN +
(hazardtype == "PH")*(ng-1)
##we now have all base functions parameters :
nEstY = sum(hazN)
##get number of parameters for survival covariates
form.surv <- cl$survival[3]
noms.form.surv <- all.vars(attr(terms(formula(paste("~",form.surv))),"variables"))
if(length(noms.form.surv)==0)
{
form.cause <- ~-1
form.causek <- vector("list",nbevt)
for(k in 1:nbevt) form.causek[[k]] <- ~-1
form.mixture <- ~-1
form.commun <- ~-1
asurv <- terms(~-1)
}
else
{
##creer la formula pour cause
form1 <- gsub("mixture","",form.surv)
form1 <- formula(paste("~",form1))
asurv1 <- terms(form1,specials="cause")
ind.cause <- attr(asurv1,"specials")$cause
if(length(ind.cause))
{
form.cause <- paste(labels(asurv1)[ind.cause],collapse="+")
form.cause <- gsub("cause","",form.cause)
form.cause <- formula(paste("~",form.cause))
}
else
{
form.cause <- ~-1
}
## formules pour causek
form.causek <- vector("list",nbevt)
for(k in 1:nbevt)
{
formk <- gsub("mixture","",form.surv)
for(kk in 1:nbevt)
{
if(kk != k) formk <- gsub(paste("cause",kk,sep=""),"",formk)
}
asurvk <- terms(formula(paste("~",formk)),specials=paste("cause",k,sep=""))
ind.causek <- attr(asurvk,"specials")$cause
if(length(ind.causek))
{
formcausek <- paste(labels(asurvk)[ind.causek],collapse="+")
formcausek <- gsub(paste("cause",k,sep=""),"",formcausek)
formcausek <- formula(paste("~",formcausek))
form.causek[[k]] <- formcausek
}
else
{
form.causek[[k]] <- ~-1
}
}
##creer la formule pour mixture
form2 <- form.surv
for( k in 1:nbevt)
{
form2 <- gsub(paste("cause",k,sep=""),"",form2)
}
form2 <- gsub("cause","",form2)
form2 <- formula(paste("~",form2))
asurv2 <- terms(form2,specials="mixture")
ind.mixture <- attr(asurv2,"specials")$mixture
if(length(ind.mixture))
{
form.mixture <- paste(labels(asurv2)[ind.mixture],collapse="+")
form.mixture <- gsub("mixture","",form.mixture)
form.mixture <- formula(paste("~",form.mixture))
}
else
{
form.mixture <- ~-1
}
## creer la formule pour ni cause ni mixture
asurv <- terms(formula(paste("~",form.surv)),specials=c("cause","mixture",paste("cause",1:nbevt,sep="")))
ind.commun <- setdiff(1:length(labels(asurv)),unlist(attr(asurv,"specials")))
if(length(ind.commun))
{
form.commun <- paste(labels(asurv)[ind.commun],collapse="+")
form.commun <- gsub("mixture","",form.commun) #si X1*mixture(X2), alors X1:mixture(X2) dans form.commun
form.commun <- gsub("cause","",form.commun) # si X1:cause(X2)
form.commun <- formula(paste("~",form.commun))
##NB: si mixture(X1)*cause(X2), X1:X2 en commun
}
else
{
form.commun <- ~-1
}
}
##I extract number of variable in each formula (through model.matrix) excluding intercept
ncols = sapply(c(form.commun, form.cause, form.mixture, form.causek), function(x, data){
mm = model.matrix(x, data)
mm = mm[,-1]
if(is.null(ncol(mm))) {return(1)}
else {return(ncol(mm))}
}, data = data)
##I also need how many parameters each kind of covariate makes
nparam = c(1, nbevt, ng, nbevt*ng)
##we now have all the survival covariates parameters :
nEstX = sum(ncols*nparam)
nEst = nEstY + nEstX
}
##A model structure is needed for all longitudinal external outcome
if(!missing(fixed)){
##Manage inputs
if(missing(mixture)) mixture = ~1
if(missing(random)) random = ~-1
if(!inherits(fixed,"formula")) stop("The argument fixed must be a formula")
if(!inherits(mixture,"formula")) stop("The argument mixture must be a formula")
if(!inherits(random,"formula")) stop("The argument random must be a formula")
if(length(fixed[[2]]) != 1){
argfunctionStrMod = "multlcmm"
} else if(is.null(link)){
argfunctionStrMod = "hlme"
} else {
argfunctionStrMod = "lcmm"
}
##let's create structure for secondary model
argumentsStrMod = list()
argumentsStrMod[["fixed"]] = fixed
argumentsStrMod[["random"]] = random
argumentsStrMod[["subject"]] = subject
argumentsStrMod[["ng"]] = 1
argumentsStrMod[["idiag"]] = idiag
argumentsStrMod[["randomY"]] = randomY
if(argfunctionStrMod %in% c("lcmm", "multlcmm", "Jointlcmm")){
argumentsStrMod[["link"]] = link
argumentsStrMod[["intnodes"]] = intnodes
}
argumentsStrMod[["epsY"]] = epsY
argumentsStrMod[["cor"]] = substitute(cor)
argumentsStrMod[["nsim"]] = nsim
argumentsStrMod[["range"]] = range
argumentsStrMod[["data"]] = data
argumentsStrMod[["maxiter"]] = 0
argumentsStrMod[["verbose"]] = FALSE
strMod = do.call(argfunctionStrMod, c(argumentsStrMod))
argumentsStrMod[["mixture"]] = mixture
argumentsStrMod[["classmb"]] = ~1
argumentsStrMod[["ng"]] = ng
argumentsStrMod[["nwg"]] = nwg
argumentsStrMod[["B"]] = as.name("strMod")
strMod = do.call(argfunctionStrMod, c(argumentsStrMod))
strMod$best[1:ng+(ng-1)] = mean(strMod$best[1:ng+(ng-1)])# pourquoi?? tous les intercepts a la meme valeur. A revoir
}
##Change general model arguments
if(method == "twoStageJoint"){
##Common argument in twoStageJoint
arguments[["data"]] = data
arguments[["ng"]] = ng
arguments[["subject"]] = subject
##technical options
arguments[["maxiter"]] = maxiter
arguments[["verbose"]] = verbose
arguments[["nproc"]] = nproc
arguments[["convB"]] = convB
arguments[["convL"]] = convL
arguments[["convG"]] = convG
arguments[["partialH"]] = partialH
##primary survival
arguments[["survival"]] = argumentsIn[["survival"]]
arguments[["hazard"]] = argumentsIn[["hazard"]]
arguments[["hazardtype"]] = argumentsIn[["hazardtype"]]
arguments[["hazardnodes"]] = argumentsIn[["hazardnodes"]]
arguments[["hazardrange"]] = argumentsIn[["hazardrange"]]
arguments[["TimeDepVar"]] = argumentsIn[["TimeDepVar"]]
arguments[["logscale"]] = argumentsIn[["logscale"]]
##Primary Jointlcmm needs transformation into lcmm to be put into longitudinal.
if(funIn == "Jointlcmm"){
if(is.null(argumentsIn[["link"]])){
argfunJoint = "hlme"
} else {
argfunJoint = "lcmm"
}
argumentsJoint = argumentsIn
argumentsJoint[["survival"]] = NULL
argumentsJoint[["hazard"]] = NULL
argumentsJoint[["hazardtype"]] = NULL
argumentsJoint[["hazardnodes"]] = NULL
argumentsJoint[["hazardrange"]] = NULL
argumentsJoint[["TimeDepVar"]] = NULL
argumentsJoint[["logscale"]] = NULL
argumentsJoint[["maxiter"]] = 0
argumentsJoint[["mixture"]] = NULL
argumentsJoint[["classmb"]] = NULL
argumentsJoint[["ng"]] = 1
argumentsJoint[["nwg"]] = FALSE
argumentsJoint[["B"]] = NULL
argumentsJoint[["verbose"]] = FALSE
argumentsJoint[["data"]] = data
modNoSurv = do.call(argfunJoint, argumentsJoint)
argumentsJoint[["mixture"]] = argumentsIn[["mixture"]]
argumentsJoint[["classmb"]]= ~1
argumentsJoint[["ng"]] = argumentsIn[["ng"]]
argumentsJoint[["nwg"]] = argumentsIn[["nwg"]]
argumentsJoint[["B"]] = modNoSurv
modNoSurv = do.call(argfunJoint, argumentsJoint)
}
##Yextern survival
if(!missing(survival)){
##manage inputs
if(!is.null(argumentsIn[["survival"]])) stop('secondary survival model is not supported with "twoStageJoint" method if primary model already includes survival')
funOut = "mpjlcmm"
##nOut : nuber of total final parameters
nOut = nIn + nEst
##index
iKeepOut = c(1:nInMB, nInMB+nEst+1:(nIn-nInMB))
iKeepIn = 1:nIn
iEst = nInMB+1:nEst
##input VC, only for keep betaa (iKeepIn)
iVCKeep = iVCIn
##Id of varcov estimates
iVCOut = c()
##list of arguments
arguments[["survival"]] = survival
arguments[["hazard"]] = hazard
arguments[["hazardtype"]] = hazardtype
arguments[["hazardnodes"]] = hazardnodes
arguments[["TimeDepVar"]] = TimeDepVar
arguments[["logscale"]] = logscale
arguments[["posfix"]] = unique(c(iKeepOut, posfix))
##what is in longitudinal ?
if(funIn == "mpjlcmm"){
arguments[["longitudinal"]] = longitudinal
} else {
arguments[["longitudinal"]] = list(model)
}
##initial values
if(missing(B)){
arguments[["B"]][iEst] = rep(0.1, nEst)
} else {
if(length(B) != length(iEst)) stop("B should be of length ", length(iEst))
arguments[["B"]][iEst] = B
}
}
##Yextern longitudinal
if(!missing(fixed)){
funOut = "mpjlcmm"
##Let's change strMod's saved call
strMod$call$data = substitute(data)
## Now join the primary and secondary model
##Informations about secondary outcome model
##number of classmb parameters to remove
nMB = ng-1
##number of remaining parameters to estimate
nStr = length(strMod$best)
nEst = nStr - nMB
##nOut : nuber of total final parameters
nOut = nIn + nEst
##index
iKeepOut = 1:nIn
iKeepIn = iKeepOut
iEst = nIn+1:nEst
##input VC, only for keep betaa (iKeepIn)
iVCKeep = iVCIn
##Id of varcov estimates
if(inherits(strMod, "multlcmm")){
nVCStr = strMod$N[4]
iVCStr = sum(strMod$N[3]) + 1:nVCStr
} else {
nVCStr = strMod$N[3]
iVCStr = sum(strMod$N[1:2]) + 1:nVCStr
}
iVCOut = nIn + iVCStr - nMB
##Liste des arguments
##on fixe nos parametres
arguments[["posfix"]] = unique(c(iKeepOut, posfix))
##On donne les modeles
if(funIn == "mpjlcmm"){
arguments[["longitudinal"]] = c(longitudinal, list(strMod))
} else if(funIn == "Jointlcmm"){
arguments[["longitudinal"]] = list(modNoSurv, strMod)
} else {
arguments[["longitudinal"]] = list(model, strMod)
} ## ici : B= prm modele entre puis prm modele ajoute
##initial values
if(missing(B)){
arguments[["B"]][iEst] = strMod$best[(nMB+1):nStr]
} else {
if(length(B) != length(iEst)) stop("B should be of length ", length(iEst))
arguments[["B"]][iEst] = B
}
}
##X extern
if(!missing(classmb)){
if(!inherits(classmb,"formula")) stop("The argument classmb must be a formula")
funOut = "mpjlcmm"
##nEst : number of MB parameters in output model
nEst1G = ncol(model.matrix(classmb, data))
nEst = nEst1G*(ng-1)
##nOut : nuber of total final parameters
nOut = nIn - nInMB + nEst
##index
iKeepOut = (nEst+1):nOut
iKeepIn = (nInMB+1):nIn
iEst = 1:nEst
##input VC, only for keep betas (iKeepIn)
iVCKeep = iVCIn-nInMB
##Id of varcov estimates (none)
iVCOut = c()
##On recree tous nos arguments
if(funIn == "mpjlcmm"){
arguments[["longitudinal"]] = longitudinal
} else if(funIn == "Jointlcmm"){
arguments[["longitudinal"]] = list(modNoSurv)
} else {
arguments[["longitudinal"]] = list(model)
}
arguments[["classmb"]] = classmb
##on ajoute des valeurs de base pour nos nouveaux estimateurs
arguments[["B"]] = rep(0, nOut)
##initial values
if(missing(B)){
arguments[["B"]][1:ng-1] = model$best[1:ng-1]
} else {
if(length(B) != length(iEst)) stop("B should be of length ", length(iEst))
arguments[["B"]][iEst] = B
}
##on fixe nos parametres
arguments[["posfix"]] = unique(c(posfix, iKeepOut))
}
}
if(method == "conditional"){
##Yextern survival
if(!missing(survival)){
## we need it all in a function in order to be able to use parametric bootstrap later on
##remaining parameters to estimate
iEst = 1:nEst
iKeepIn = 1:nIn
iKeepOut = 1:nIn+nEst+2
nOut = nEst+2
##Id of varcov estimates to keep in bootstrap
iVCKeep = iVCIn
iVCOut = c()
nVCIn = 0
##We need what is inside of longitudinal to still exist in the worker
argumentsIn[["longitudinal"]] = eval(argumentsIn[["longitudinal"]])
conditionalS = function(model,
data,
survival,
hazard,
hazardtype,
hazardnodes = NULL,
TimeDepVar = NULL,
logscale,
subject,
ng,
B,
link,
iEst,
maxiter,
verbose,
argumentsIn,
funIn,
nproc,
convB,
convL,
convG){
argumentsInEdit = argumentsIn
argumentsInEdit[["B"]] = B[iKeepOut]
argumentsInEdit[["maxiter"]] = 0
argumentsInEdit[["verbose"]] = F
argumentsInEdit[["nproc"]] = nproc
argumentsInEdit[["data"]] = data
model = do.call(funIn, argumentsInEdit)
B = B[iEst]
predCl = predictClass(model, data)
##First : let's compute P(C|\tilde C) (\tilde C : A)
pAlY = sapply(1:ng, function(g){
return(as.numeric(predCl[,2] == g))
})
pClY = as.matrix(predCl[,3:(2+ng)])
if(any(is.nan(pClY))) stop("NaN in posterior classification probability")
pA = apply(pAlY, 2, mean)
pClA = t(pAlY)%*%pClY/(model$ns*pA)
if(det(pClA) == 0 | is.na(det(pClA))) stop("Computed error matrix is singular. One class might be empty")
##Then : let's add it to dataset for each individual
indivProb = pAlY%*%pClA
indivProb = cbind(predCl[,1], indivProb)
colnames(indivProb)[1] = subject
data = merge(data, indivProb, by = subject)
##We need dummy Y for the model to run
data$dummyY = 1
##With some type of input model, prob does not have the same name
if(!"prob1" %in% colnames(data)){
for(i in 1:ng){
data[[paste0("prob", i)]] = data[[paste0("probYT", i)]]
}
}
##Finally : we need to build the model for ppriors !
arguments = list()
arguments[["data"]] = data
arguments[["fixed"]] = dummyY~1
arguments[["mixture"]] = ~-1
arguments[["survival"]] = survival
arguments[["hazard"]] = hazard
arguments[["hazardtype"]] = hazardtype
arguments[["hazardnodes"]] = hazardnodes
arguments[["TimeDepVar"]] = TimeDepVar
arguments[["logscale"]] = logscale
arguments[["subject"]] = subject
arguments[["classmb"]] = ~-1
arguments[["ng"]] = ng
arguments[["pprior"]] = c("prob1", "prob2")
arguments[["posfix"]] = 1:2+length(iEst)
##technical options
arguments[["maxiter"]] = maxiter
arguments[["verbose"]] = verbose
arguments[["nproc"]] = nproc
arguments[["convB"]] = convB
arguments[["convL"]] = convL
arguments[["convG"]] = convG
arguments[["B"]] = c(B[iEst], 1, 0.000001)
res = do.call("Jointlcmm", arguments)
res$call = match.call()
return(res)
}
##we need to build the model
arguments[["data"]] = data
arguments[["survival"]] = survival
arguments[["hazard"]] = hazard
arguments[["hazardtype"]] = hazardtype
arguments[["hazardnodes"]] = hazardnodes
arguments[["TimeDepVar"]] = TimeDepVar
arguments[["logscale"]] = logscale