-
Notifications
You must be signed in to change notification settings - Fork 144
/
lmer.R
2703 lines (2517 loc) · 109 KB
/
lmer.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
## NB: doc in ../man/*.Rd ***not*** auto generated
## FIXME: need to document S3 methods better (can we pull from r-forge version?)
##' Fit a linear mixed model (LMM)
lmer <- function(formula, data=NULL, REML = TRUE,
control = lmerControl(), start = NULL
, verbose = 0L
, subset, weights, na.action, offset
, contrasts = NULL
, devFunOnly=FALSE
)
## , ...)
{
mc <- mcout <- match.call()
missCtrl <- missing(control)
## see functions in modular.R for the body ..
if (!missCtrl && !inherits(control, "lmerControl")) {
if(!is.list(control)) stop("'control' is not a list; use lmerControl()")
## back-compatibility kluge
warning("passing control as list is deprecated: please use lmerControl() instead",
immediate.=TRUE)
control <- do.call(lmerControl, control)
}
## if (!is.null(list(...)[["family"]])) {
## warning("calling lmer with 'family' is deprecated; please use glmer() instead")
## mc[[1]] <- quote(lme4::glmer)
## if(missCtrl) mc$control <- glmerControl()
## return(eval(mc, parent.frame(1L)))
## }
mc$control <- control ## update for back-compatibility kluge
## https://github.com/lme4/lme4/issues/50
## parse data and formula
mc[[1]] <- quote(lme4::lFormula)
lmod <- eval(mc, parent.frame(1L))
mcout$formula <- lmod$formula
lmod$formula <- NULL
if (is.matrix(y <- model.response(lmod$fr)) && ncol(y) > 1) {
stop("can't handle matrix-valued responses: consider using refit()")
}
## create deviance function for covariance parameters (theta)
devfun <- do.call(mkLmerDevfun,
c(lmod,
list(start=start, verbose=verbose, control=control)))
if (devFunOnly) return(devfun)
## optimize deviance function over covariance parameters
if (identical(control$optimizer,"none"))
stop("deprecated use of optimizer=='none'; use NULL instead")
opt <- if (length(control$optimizer)==0) {
s <- getStart(start, environment(devfun)$pp)
list(par=s,fval=devfun(s),
conv=1000,message="no optimization")
} else {
optimizeLmer(devfun, optimizer = control$optimizer,
restart_edge = control$restart_edge,
boundary.tol = control$boundary.tol,
control = control$optCtrl,
verbose=verbose,
start=start,
calc.derivs=control$calc.derivs,
use.last.params=control$use.last.params)
}
cc <- checkConv(attr(opt,"derivs"), opt$par,
ctrl = control$checkConv,
lbound = environment(devfun)$lower)
mkMerMod(environment(devfun), opt, lmod$reTrms, fr = lmod$fr,
mc = mcout, lme4conv=cc) ## prepare output
}## { lmer }
##' Fit a generalized linear mixed model (GLMM)
glmer <- function(formula, data=NULL
, family = gaussian
, control = glmerControl()
, start = NULL
, verbose = 0L
, nAGQ = 1L
, subset, weights, na.action, offset, contrasts = NULL
, mustart, etastart
, devFunOnly = FALSE)
{
if (!inherits(control, "glmerControl")) {
if(!is.list(control)) stop("'control' is not a list; use glmerControl()")
## back-compatibility kluge
if (class(control)[1]=="lmerControl") {
warning("please use glmerControl() instead of lmerControl()",
immediate.=TRUE)
control <-
## unpack sub-lists
c(control[!names(control) %in% c("checkConv","checkControl")],
control$checkControl,control$checkConv)
control["restart_edge"] <- NULL ## not implemented for glmer
} else {
msg <- "Use control=glmerControl(..) instead of passing a list"
if(length(cl <- class(control))) {
msg <- paste(msg, "of class", dQuote(cl[1]))
}
warning(msg, immediate.=TRUE)
}
control <- do.call(glmerControl, control)
}
mc <- mcout <- match.call()
## family-checking code duplicated here and in glFormula (for now) since
## we really need to redirect at this point; eventually deprecate formally
## and clean up
if (is.character(family))
family <- get(family, mode = "function", envir = parent.frame(2))
if( is.function(family)) family <- family()
if (isTRUE(all.equal(family, gaussian()))) {
## redirect to lmer (with warning)
warning("calling glmer() with family=gaussian (identity link) as a shortcut to lmer() is deprecated;",
" please call lmer() directly")
mc[[1]] <- quote(lme4::lmer)
mc["family"] <- NULL # to avoid an infinite loop
return(eval(mc, parent.frame()))
}
## see https://github.com/lme4/lme4/issues/50
## parse the formula and data
mc[[1]] <- quote(lme4::glFormula)
glmod <- eval(mc, parent.frame(1L))
mcout$formula <- glmod$formula
glmod$formula <- NULL
if (is.matrix(y <- model.response(glmod$fr))
&& ((family$family != "binomial" && ncol(y) > 1) ||
(ncol(y) >2))) {
stop("can't handle matrix-valued responses: consider using refit()")
}
## create deviance function for covariance parameters (theta)
nAGQinit <- if(control$nAGQ0initStep) 0L else 1L
devfun <- do.call(mkGlmerDevfun, c(glmod, list(verbose = verbose,
control = control,
nAGQ = nAGQinit)))
if (nAGQ==0 && devFunOnly) return(devfun)
## optimize deviance function over covariance parameters
## FIXME: perhaps should be in glFormula instead??
if (is.list(start)) {
start.bad <- setdiff(names(start),c("theta","fixef"))
if (length(start.bad)>0) {
stop(sprintf("bad name(s) for start vector (%s); should be %s and/or %s",
paste(start.bad,collapse=", "),
shQuote("theta"),
shQuote("fixef")),call.=FALSE)
}
if (!is.null(start$fixef) && nAGQ==0)
stop("should not specify both start$fixef and nAGQ==0")
}
## FIX ME: allow calc.derivs, use.last.params etc. if nAGQ=0
if(control$nAGQ0initStep) {
opt <- optimizeGlmer(devfun,
optimizer = control$optimizer[[1]],
## DON'T try fancy edge tricks unless nAGQ=0 explicitly set
restart_edge=if (nAGQ==0) control$restart_edge else FALSE,
boundary.tol=if (nAGQ==0) control$boundary.tol else 0,
control = control$optCtrl,
start=start,
nAGQ = 0,
verbose=verbose,
calc.derivs=FALSE)
}
if(nAGQ > 0L) {
## update deviance function to include fixed effects as inputs
devfun <- updateGlmerDevfun(devfun, glmod$reTrms, nAGQ = nAGQ)
if (control$nAGQ0initStep) {
start <- updateStart(start,theta=opt$par)
}
## if nAGQ0 was skipped
## we don't actually need to do anything here, it seems --
## getStart gets called again in optimizeGlmer
if (devFunOnly) return(devfun)
## reoptimize deviance function over covariance parameters and fixed effects
opt <- optimizeGlmer(devfun,
optimizer = control$optimizer[[2]],
restart_edge=control$restart_edge,
boundary.tol=control$boundary.tol,
control = control$optCtrl,
start=start,
nAGQ=nAGQ,
verbose = verbose,
stage=2,
calc.derivs=control$calc.derivs,
use.last.params=control$use.last.params)
}
cc <- if (!control$calc.derivs) NULL else {
if (verbose > 10) cat("checking convergence\n")
checkConv(attr(opt,"derivs"),opt$par,
ctrl = control$checkConv,
lbound=environment(devfun)$lower)
}
## prepare output
mkMerMod(environment(devfun), opt, glmod$reTrms, fr = glmod$fr,
mc = mcout, lme4conv=cc)
}## {glmer}
##' Fit a nonlinear mixed-effects model
nlmer <- function(formula, data=NULL, control = nlmerControl(), start = NULL, verbose = 0L,
nAGQ = 1L, subset, weights, na.action, offset,
contrasts = NULL, devFunOnly = FALSE)
{
vals <- nlformula(mc <- match.call())
p <- ncol(X <- vals$X)
if ((rankX <- rankMatrix(X)) < p)
stop(gettextf("rank of X = %d < ncol(X) = %d", rankX, p))
rho <- list2env(list(verbose=verbose,
tolPwrss=0.001, # this is reset to the tolPwrss argument's value later
resp=vals$resp,
lower=vals$reTrms$lower),
parent=parent.frame())
rho$pp <- do.call(merPredD$new,
c(vals$reTrms[c("Zt","theta","Lambdat","Lind")],
list(X=X, n=length(vals$respMod$mu), Xwts=vals$respMod$sqrtXwt,
beta0=qr.coef(qr(X), unlist(lapply(vals$pnames, get,
envir = rho$resp$nlenv))))))
rho$u0 <- rho$pp$u0
rho$beta0 <- rho$pp$beta0
## deviance as a function of theta only :
devfun <- mkdevfun(rho, 0L, verbose=verbose, control=control)
if (devFunOnly && !nAGQ) return(devfun)
devfun(rho$pp$theta) # initial coarse evaluation to get u0 and beta0
rho$u0 <- rho$pp$u0
rho$beta0 <- rho$pp$beta0
rho$tolPwrss <- control$tolPwrss # Reset control parameter (the initial optimization is coarse)
## set lower and upper bounds: if user-specified, select
## only the ones corresponding to random effects
if (!is.null(lwr <- control$optCtrl$lower)) {
rho$lower <- lwr[seq_along(rho$lower)]
control$optCtrl$lower <- NULL
}
upper <- rep(Inf, length(rho$lower))
if (!is.null(upr <- control$optCtrl$upper)) {
upper <- upr[seq_along(rho$lower)]
control$optCtrl$upper <- NULL
}
opt <- optwrap(control$optimizer[[1]], devfun, rho$pp$theta,
lower=rho$lower,
upper=upper,
control=control$optCtrl,
adj=FALSE)
rho$control <- attr(opt,"control")
if (nAGQ > 0L) {
## set lower/upper to values already harvested from control$optCtrl$upper
rho$lower <- if(!is.null(lwr)) lwr else c(rho$lower, rep.int(-Inf, length(rho$beta0)))
upper <- if(!is.null(upr)) upr else c( upper, rep.int( Inf, length(rho$beta0)))
rho$u0 <- rho$pp$u0
rho$dpars <- seq_along(rho$pp$theta)
## fixed-effect parameters
rho$beta0 <- pmin(upper[-rho$dpars],
pmax(rho$pp$beta0,rho$lower[-rho$dpars]))
if (nAGQ > 1L) {
if (length(vals$reTrms$flist) != 1L || length(vals$reTrms$cnms[[1]]) != 1L)
stop("nAGQ > 1 is only available for models with a single, scalar random-effects term")
rho$fac <- vals$reTrms$flist[[1]]
}
devfun <- mkdevfun(rho, nAGQ, verbose=verbose, control=control)
if (devFunOnly) return(devfun)
opt <- optwrap(control$optimizer[[2]], devfun,
par = c(rho$pp$theta, rho$beta0),
lower = rho$lower,
upper = upper,
control = control$optCtrl,
adj = TRUE, verbose=verbose)
}
mkMerMod(environment(devfun), opt, vals$reTrms, fr = vals$frame, mc = mc)
}## {nlmer}
## R 3.1.0 devel [2013-08-05]: This does not help yet
if(getRversion() >= "3.1.0") utils::suppressForeignCheck("nlmerAGQ")
if(getRversion() < "3.1.0") dontCheck <- identity
## *not* exported (had help page till early 2018)
## -> issue #92: -> also look at devfun2() in ./profile.R (which returns class!)
##' Create a deviance evaluation function from a predictor and a response module
##' @param rho an `environment` already containing `verbose` and tolPwrss
##' @param nAGQ for glmer/nlmer: #{AGQ steps}; 0 <==> Laplace
##' @param maxit maximal number of PIRLS iterations
##' @param verbose integer specifying if outputs should be produced
##' @param control a list as from lmerControl() etc
mkdevfun <- function(rho, nAGQ=1L, maxit = if(extends(rho.cld, "nlsResp")) 300L else 100L,
verbose=0, control=list()) {
## FIXME: should nAGQ be automatically embedded in rho?
stopifnot(is.environment(rho), ## class definition, compute and save :
extends(rho.cld <- getClass(class(rho$resp)), "lmResp"))
## silence R CMD check warnings *locally* in this function
## (clearly preferred to using globalVariables() !]
fac <- pp <- resp <- lp0 <- compDev <- dpars <- baseOffset <- tolPwrss <-
pwrssUpdate <- ## <-- even though it's a function below
GQmat <- nlmerAGQ <- NULL
## The deviance function (to be returned, with 'rho' as its environment):
ff <-
if (extends(rho.cld, "lmerResp")) {
rho$lmer_Deviance <- lmer_Deviance
function(theta) .Call(lmer_Deviance, pp$ptr(), resp$ptr(), as.double(theta))
} else if (extends(rho.cld, "glmResp")) {
## control values will override rho values *if present*
if (!is.null(tp <- control$tolPwrss)) rho$tolPwrss <- tp
if (!is.null(cd <- control$ compDev)) rho$compDev <- cd
if (nAGQ == 0L)
function(theta) {
resp$updateMu(lp0)
pp$setTheta(theta)
p <- pwrssUpdate(pp, resp, tol=tolPwrss, GQmat=GHrule(0L),
compDev=compDev, maxit=maxit, verbose=verbose)
resp$updateWts()
p
}
else ## nAGQ > 0
function(pars) {
## pp$setDelu(rep(0, length(pp$delu)))
resp$setOffset(baseOffset)
resp$updateMu(lp0)
pp$setTheta(as.double(pars[dpars])) # theta is first part of pars
spars <- as.numeric(pars[-dpars])
offset <- if (length(spars)==0) baseOffset else baseOffset + pp$X %*% spars
resp$setOffset(offset)
p <- pwrssUpdate(pp, resp, tol=tolPwrss, GQmat=GQmat,
compDev=compDev, grpFac=fac, maxit=maxit, verbose=verbose)
resp$updateWts()
p
}
} else if (extends(rho.cld, "nlsResp")) {
if (nAGQ <= 1L) {
rho$nlmerLaplace <- nlmerLaplace
rho$tolPwrss <- control$tolPwrss
rho$maxit <- maxit
switch(nAGQ + 1L,
function(theta)
.Call(nlmerLaplace, pp$ptr(), resp$ptr(), as.double(theta),
as.double(u0), beta0, verbose, FALSE, tolPwrss, maxit),
function(pars)
.Call(nlmerLaplace, pp$ptr(), resp$ptr(), pars[dpars],
u0, pars[-dpars], verbose, TRUE, tolPwrss, maxit))
} else {
stop("nAGQ > 1 not yet implemented for nlmer models")
rho$nlmerAGQ <- nlmerAGQ
rho$GQmat <- GHrule(nAGQ)
## function(pars) {
## .Call(nlmerAGQ, ## <- dontCheck(nlmerAGQ) should work according to docs but does not
## pp$ptr(), resp$ptr(), fac, GQmat, pars[dpars],
## u0, pars[-dpars], tolPwrss)
##}
}
}
else stop("code not yet written")
environment(ff) <- rho
ff
}
## Determine a step factor that will reduce the pwrss
##
## The penalized, weighted residual sum of squares (pwrss) is the sum
## of the weighted residual sum of squares from the resp module and
## the squared length of u from the predictor module. The predictor module
## contains a base value and an increment for the coefficients.
## @title Determine a step factor
## @param pp predictor module
## @param resp response module
## @param verbose logical value determining verbose output
## @return NULL if successful
## @note Typically all this is done in the C++ code.
## The R code is for debugging and comparisons of
## results.
## stepFac <- function(pp, resp, verbose, maxSteps = 10) {
## stopifnot(is.numeric(maxSteps), maxSteps >= 2)
## pwrss0 <- resp$wrss() + pp$sqrL(0)
## for (fac in 2^(-(0:maxSteps))) {
## wrss <- resp$updateMu(pp$linPred(fac))
## pwrss1 <- wrss + pp$sqrL(fac)
## if (verbose > 3L)
## cat(sprintf("pwrss0=%10g, diff=%10g, fac=%6.4f\n",
## pwrss0, pwrss0 - pwrss1, fac))
## if (pwrss1 <= pwrss0) {
## pp$installPars(fac)
## return(NULL)
## }
## }
## stop("step factor reduced below ",signif(2^(-maxSteps),2)," without reducing pwrss")
## }
RglmerWrkIter <- function(pp, resp, uOnly=FALSE) {
pp$updateXwts(resp$sqrtWrkWt())
pp$updateDecomp()
pp$updateRes(resp$wtWrkResp())
if (uOnly) pp$solveU() else pp$solve()
resp$updateMu(pp$linPred(1)) # full increment
resp$resDev() + pp$sqrL(1)
}
##' @param pp pred module
##' @param resp resp module
##' @param tol numeric tolerance
##' @param GQmat matrix of Gauss-Hermite quad info
##' @param compDev compute in C++ (as opposed to doing as much as possible in R)
##' @param grpFac grouping factor (normally found in environment ..)
##' @param verbose verbosity, of course
glmerPwrssUpdate <- function(pp, resp, tol, GQmat, compDev=TRUE, grpFac=NULL, maxit = 70L, verbose=0) {
nAGQ <- nrow(GQmat)
if (compDev) {
if (nAGQ < 2L)
return(.Call(glmerLaplace, pp$ptr(), resp$ptr(),
nAGQ, tol, as.integer(maxit),
verbose))
return(.Call(glmerAGQ, pp$ptr(), resp$ptr(),
tol, as.integer(maxit),
GQmat, grpFac, verbose))
}
### does this show anywhere ??? [i.e. is it ever used in our checks/examples/scripts/vignettes ?
### message("glmerPwrssUpdate(*, compDev=FALSE) --> using more R, no direct .Call() to C.") # [DBG] only
oldpdev <- .Machine$double.xmax
uOnly <- nAGQ == 0L
i <- 0
repeat {
## oldu <- pp$delu
## olddelb <- pp$delb
pdev <- RglmerWrkIter(pp, resp, uOnly=uOnly)
if (verbose > 2) cat(i,": ",pdev,"\n",sep="")
## check convergence first so small increases don't trigger errors
if (is.na(pdev)) stop("encountered NA in PWRSS update")
if (abs((oldpdev - pdev) / pdev) < tol)
break
## if (pdev > oldpdev) {
## ## try step-halving
## ## browser()
## k <- 0
## while (k < 10 && pdev > oldpdev) {
## pp$setDelu((oldu + pp$delu)/2.)
## if (!uOnly) pp$setDelb((olddelb + pp$delb)/2.)
## pdev <- RglmerWrkIter(pp, resp, uOnly=uOnly)
## k <- k+1
## }
## }
if (pdev > oldpdev) stop("PIRLS update failed")
oldpdev <- pdev
i <- i+1
}
resp$Laplace(pp$ldL2(), 0., pp$sqrL(1)) ## FIXME: should 0. be pp$ldRX2 ?
}
## create a deviance evaluation function that uses the sigma parameters
## df2 <- function(dd) {
## stopifnot(is.function(dd),
## length(formals(dd)) == 1L,
## is((rem <- (rho <- environment(dd))$rem), "Rcpp_reModule"),
## is((fem <- rho$fem), "Rcpp_deFeMod"),
## is((resp <- rho$resp), "Rcpp_lmerResp"),
## all((lower <- rem$lower) == 0))
## Lind <- rem$Lind
## n <- length(resp$y)
## function(pars) {
## sigma <- pars[1]
## sigsq <- sigma * sigma
## sigmas <- pars[-1]
## theta <- sigmas/sigma
## rem$theta <- theta
## resp$updateMu(numeric(n))
## solveBetaU(rem, fem, resp$sqrtXwt, resp$wtres)
## resp$updateMu(rem$linPred1(1) + fem$linPred1(1))
## n * log(2*pi*sigsq) + (resp$wrss + rem$sqrLenU)/sigsq + rem$ldL2
## }
## }
## bootMer() ---> now in ./bootMer.R
## Methods for the merMod class
## Anova for merMod objects
##
## @title anova() for merMod objects
## @param a merMod object
## @param ... further such objects
## @param refit should objects be refitted with ML (if applicable)
## @return an "anova" data frame; the traditional (S3) result of anova()
anovaLmer <- function(object, ..., refit = TRUE, model.names=NULL) {
mCall <- match.call(expand.dots = TRUE)
dots <- list(...)
.sapply <- function(L, FUN, ...) unlist(lapply(L, FUN, ...))
modp <- (as.logical(vapply(dots, is, NA, "merMod")) |
as.logical(vapply(dots, is, NA, "lm")))
if (any(modp)) { ## multiple models - form table
## opts <- dots[!modp]
mods <- c(list(object), dots[modp])
nobs.vec <- vapply(mods, nobs, 1L)
if (var(nobs.vec) > 0)
stop("models were not all fitted to the same size of dataset")
## model names
if (is.null(mNms <- model.names))
mNms <- vapply(as.list(mCall)[c(FALSE, TRUE, modp)], deparse1, "")
## HACK to try to identify model names in situations such as
## 'do.call(anova,list(model1,model2))' where the model names
## are lost in the call stack ... this doesn't quite work but might
## be useful for future attempts?
## maxdepth <- -2
## depth <- -1
## while (depth >= maxdepth &
## all(grepl("S4 object of class structure",mNms))) {
## xCall <- match.call(call=sys.call(depth))
## mNms <- .sapply(as.list(xCall)[c(FALSE, TRUE, modp)], deparse)
## depth <- depth-1
## }
## if (depth < maxdepth) {
if (any(substr(mNms, 1,4) == "new(") ||
any(duplicated(mNms)) || ## <- only if S4 objects are *not* properly deparsed
max(nchar(mNms)) > 200) {
warning("failed to find model names, assigning generic names")
mNms <- paste0("MODEL",seq_along(mNms))
}
if (length(mNms) != length(mods))
stop("model names vector and model list have different lengths")
names(mods) <- sub("@env$", '', mNms) # <- hack
models.reml <- vapply(mods, function(x) is(x,"merMod") && isREML(x), NA)
models.GHQ <- vapply(mods, function(x) is(x,"glmerMod") && getME(x,"devcomp")$dims["nAGQ"]>1 , NA)
if (any(models.GHQ) && any(vapply(mods, function(x) is(x,"glm"), NA)))
stop("GLMMs with nAGQ>1 have log-likelihoods incommensurate with glm() objects")
if (refit) {
## message only if at least one models is REML:
if (any(models.reml)) message("refitting model(s) with ML (instead of REML)")
mods[models.reml] <- lapply(mods[models.reml], refitML)
} else { ## check that models are consistent (all REML or all ML)
if(any(models.reml) && any(!models.reml))
warning("some models fit with REML = TRUE, some not")
}
## devs <- sapply(mods, deviance)
llks <- lapply(mods, logLik)
## Order models by increasing degrees of freedom:
ii <- order(npar <- vapply(llks, attr, FUN.VALUE=numeric(1), "df"))
mods <- mods[ii]
llks <- llks[ii]
npar <- npar [ii]
calls <- lapply(mods, getCall)
data <- lapply(calls, `[[`, "data")
if(!all(vapply(data, identical, NA, data[[1]])))
stop("all models must be fit to the same data object")
header <- paste("Data:", abbrDeparse(data[[1]]))
subset <- lapply(calls, `[[`, "subset")
if(!all(vapply(subset, identical, NA, subset[[1]])))
stop("all models must use the same subset")
if (!is.null(subset[[1]]))
header <- c(header, paste("Subset:", abbrDeparse(subset[[1]])))
llk <- unlist(llks)
chisq <- 2 * pmax(0, c(NA, diff(llk)))
dfChisq <- c(NA, diff(npar))
val <- data.frame(npar = npar,
## afraid to swap in vapply here; wondering
## why .sapply was needed in the first place ...
AIC = .sapply(llks, AIC), # FIXME? vapply()
BIC = .sapply(llks, BIC), # " "
logLik = llk,
deviance = -2*llk,
Chisq = chisq,
Df = dfChisq,
"Pr(>Chisq)" = ifelse(dfChisq==0,NA,pchisq(chisq, dfChisq, lower.tail = FALSE)),
row.names = names(mods), check.names = FALSE)
class(val) <- c("anova", class(val))
forms <- lapply(lapply(calls, `[[`, "formula"), deparse1)
structure(val,
heading = c(header, "Models:",
paste(rep.int(names(mods), lengths(forms)),
unlist(forms), sep = ": ")))
}
else { ## ------ single model ---------------------
if (length(dots)>0) {
warnmsg <- "additional arguments ignored"
nd <- names(dots)
nd <- nd[nzchar(nd)]
if (length(nd)>0) {
warnmsg <- paste0(warnmsg,": ",
paste(sQuote(nd),collapse=", "))
}
warning(warnmsg)
}
dc <- getME(object, "devcomp")
X <- getME(object, "X")
stopifnot(length(asgn <- attr(X, "assign")) == dc$dims[["p"]])
ss <- as.vector(object@pp$RX() %*% object@beta)^2
names(ss) <- colnames(X)
terms <- terms(object)
nmeffects <- attr(terms, "term.labels")[unique(asgn)]
if ("(Intercept)" %in% names(ss))
nmeffects <- c("(Intercept)", nmeffects)
ss <- unlist(lapply(split(ss, asgn), sum))
stopifnot(length(ss) == length(nmeffects))
df <- lengths(split(asgn, asgn))
## dfr <- unlist(lapply(split(dfr, asgn), function(x) x[1]))
ms <- ss/df
f <- ms/(sigma(object)^2)
## No longer provide p-values, but still the F statistic (may not be F distributed):
##
## P <- pf(f, df, dfr, lower.tail = FALSE)
## table <- data.frame(df, ss, ms, dfr, f, P)
table <- data.frame(df, ss, ms, f)
dimnames(table) <-
list(nmeffects,
## c("npar", "Sum Sq", "Mean Sq", "Denom", "F value", "Pr(>F)"))
c("npar", "Sum Sq", "Mean Sq", "F value"))
if ("(Intercept)" %in% nmeffects)
table <- table[-match("(Intercept)", nmeffects), ]
structure(table, heading = "Analysis of Variance Table",
class = c("anova", "data.frame"))
}
}## {anovaLmer}
##' @importFrom stats anova
##' @S3method anova merMod
anova.merMod <- anovaLmer
##' @S3method as.function merMod
as.function.merMod <- function(x, ...) {
rho <- list2env(list(resp = x@resp$copy(),
pp = x@pp$copy(),
beta0 = x@beta,
u0 = x@u),
parent=as.environment("package:lme4"))
## FIXME: extract verbose [, maxit] and control
mkdevfun(rho, getME(x, "devcomp")$dims[["nAGQ"]], ...)
}
## coef() method for all kinds of "mer", "*merMod", ... objects
## ------ should work with fixef() + ranef() alone
coefMer <- function(object, ...)
{
if(...length())
warning('arguments named ', paste(sQuote(...names()), collapse = ", "),
' ignored')
fef <- data.frame(rbind(fixef(object)), check.names = FALSE)
ref <- ranef(object, condVar = FALSE)
## check for variables in RE but missing from FE, fill in zeros in FE accordingly
refnames <- unlist(lapply(ref,colnames))
nmiss <- length(missnames <- setdiff(refnames,names(fef)))
if (nmiss > 0) {
fillvars <- setNames(data.frame(rbind(rep(0,nmiss))),missnames)
fef <- cbind(fillvars,fef)
}
val <- lapply(ref, function(x)
fef[rep.int(1L, nrow(x)),,drop = FALSE])
for (i in seq_along(val)) {
refi <- ref[[i]]
row.names(val[[i]]) <- row.names(refi)
nmsi <- colnames(refi)
if (!all(nmsi %in% names(fef)))
stop("unable to align random and fixed effects")
for (nm in nmsi) val[[i]][[nm]] <- val[[i]][[nm]] + refi[,nm]
}
class(val) <- "coef.mer"
val
} ## {coefMer}
##' @importFrom stats coef
##' @S3method coef merMod
coef.merMod <- coefMer
## FIXME: should these values (i.e. ML criterion for REML models
## and vice versa) be computed and stored in the object in the first place?
##' @importFrom stats deviance
##' @S3method deviance merMod
deviance.merMod <- function(object, REML = NULL, ...) {
## type = c("conditional", "unconditional", "penalized"),
## relative = TRUE, ...) {
if (isGLMM(object)) {
return(sum(residuals(object,type="deviance")^2))
## ------------------------------------------------------------
## proposed change to deviance function for GLMMs
## ------------------------------------------------------------
## @param type Type of deviance (can be unconditional,
## penalized, conditional)
## @param relative Should deviance be shifted relative to a
## saturated model? (only available with type == penalized or
## conditional)
## ------------------------------------------------------------
## ans <- switch(type[1],
## unconditional = {
## if (relative) {
## stop("unconditional and relative deviance is undefined")
## }
## c(-2 * logLik(object))
## },
## penalized = {
## sqrL <- object@pp$sqrL(1)
## if (relative) {
## object@resp$resDev() + sqrL
## } else {
## useSc <- unname(getME(gm1, "devcomp")$dims["useSc"])
## qLog2Pi <- unname(getME(object, "q")) * log(2 * pi)
## object@resp$aic() - (2 * useSc) + sqrL + qLog2Pi
## }
## },
## conditional = {
## if (relative) {
## object@resp$resDev()
## } else {
## useSc <- unname(getME(gm1, "devcomp")$dims["useSc"])
## object@resp$aic() - (2 * useSc)
## }
## })
## return(ans)
}
if (isREML(object) && is.null(REML)) {
warning("deviance() is deprecated for REML fits; use REMLcrit for the REML criterion or deviance(.,REML=FALSE) for deviance calculated at the REML fit")
return(devCrit(object, REML=TRUE))
}
devCrit(object, REML=FALSE)
}
REMLcrit <- function(object) {
devCrit(object, REML=TRUE)
}
## original deviance.merMod -- now wrapped by REMLcrit
## REML=NULL:
## if REML fit return REML criterion
## if ML fit, return deviance
## REML=TRUE:
## if not LMM, stop.
## if ML fit, compute and return REML criterion
## if REML fit, return REML criterion
## REML=FALSE:
## if ML fit, return deviance
## if REML fit, compute and return deviance
devCrit <- function(object, REML = NULL) {
## cf. (1) lmerResp::Laplace in respModule.cpp
## (2) section 5.6 of lMMwR, listing lines 34-42
if (isTRUE(REML) && !isLMM(object))
stop("can't compute REML deviance for a non-LMM")
cmp <- object@devcomp$cmp
if (is.null(REML) || is.na(REML[1]))
REML <- isREML(object)
if (REML) {
if (isREML(object)) {
cmp[["REML"]]
} else {
## adjust ML results to REML
lnum <- log(2*pi*cmp[["pwrss"]])
n <- object@devcomp$dims[["n"]]
nmp <- n - length(object@beta)
ldW <- sum(log(weights(object, method = "prior")))
- ldW + cmp[["ldL2"]] + cmp[["ldRX2"]] + nmp*(1 + lnum - log(nmp))
}
} else {
if (!isREML(object)) {
cmp[["dev"]]
} else {
## adjust REML results to ML
n <- object@devcomp$dims[["n"]]
lnum <- log(2*pi*cmp[["pwrss"]])
ldW <- sum(log(weights(object, method = "prior")))
- ldW + cmp[["ldL2"]] + n*(1 + lnum - log(n))
}
}
}
## copied from stats:::safe_pchisq
safe_pchisq <- function (q, df, ...) {
df[df <= 0] <- NA
pchisq(q = q, df = df, ...)
}
##' @importFrom stats drop1
##' @S3method drop1 merMod
drop1.merMod <- function(object, scope, scale = 0, test = c("none", "Chisq", "user"),
k = 2, trace = FALSE,
sumFun=NULL, ...) {
evalhack <- "formulaenv"
test <- match.arg(test)
if ((test=="user" && is.null(sumFun)) ||
((test!="user" && !is.null(sumFun))))
stop(sQuote("sumFun"),' must be specified if (and only if) test=="user"')
tl <- attr(terms(object), "term.labels")
if(missing(scope)) scope <- drop.scope(object)
else {
if(!is.character(scope)) {
scope <- attr(terms(getFixedFormula(update.formula(object, scope))),
"term.labels")
}
if(!all(match(scope, tl, 0L) > 0L))
stop("scope is not a subset of term labels")
}
ns <- length(scope)
if (is.null(sumFun)) {
sumFun <- function(x,scale,k,...)
setNames(extractAIC(x,scale,k,...),c("df","AIC"))
}
ss <- sumFun(object, scale=scale, k=k, ...)
ans <- matrix(nrow = ns + 1L, ncol = length(ss),
dimnames = list(c("<none>", scope), names(ss)))
ans[1, ] <- ss
n0 <- nobs(object, use.fallback = TRUE)
env <- environment(formula(object)) # perhaps here is where trouble begins??
for(i in seq_along(scope)) { ## was seq(ns), failed on empty scope
tt <- scope[i]
if(trace > 1) {
cat("trying -", tt, "\n", sep='')
flush.console()
}
## FIXME: make this more robust, somehow?
## three choices explored so far:
## (1) evaluate nfit in parent frame: tests in inst/tests/test-formulaEval.R
## will fail on lapply(m_data_List,drop1)
## (formula environment contains r,x,y,z but not d)
## (2) evaluate nfit in frame of formula: tests will fail when data specified and formula is character
## (3) update with data=NULL: fails when ...
##
if (evalhack %in% c("parent","formulaenv")) {
nfit <- update(object,
as.formula(paste("~ . -", tt)),
evaluate = FALSE)
## nfit <- eval(nfit, envir = env) # was eval.parent(nfit)
if (evalhack=="parent") {
nfit <- eval.parent(nfit)
} else if (evalhack=="formulaenv") {
nfit <- eval(nfit,envir=env)
}
} else {
nfit <- update(object,
as.formula(paste("~ . -", tt)),data=NULL,
evaluate = FALSE)
nfit <- eval(nfit,envir=env)
}
if (test=="user") {
ans[i+1, ] <- sumFun(object, nfit, scale=scale, k=k, ...)
} else {
ans[i+1, ] <- sumFun(nfit, scale, k = k, ...)
}
nnew <- nobs(nfit, use.fallback = TRUE)
if(all(is.finite(c(n0, nnew))) && nnew != n0)
stop("number of rows in use has changed: remove missing values?")
}
if (test=="user") {
aod <- as.data.frame(ans)
} else {
dfs <- ans[1L, 1L] - ans[, 1L]
dfs[1L] <- NA
aod <- data.frame(npar = dfs, AIC = ans[,2])
if(test == "Chisq") {
## reconstruct deviance from AIC (ugh)
dev <- ans[, 2L] - k*ans[, 1L]
dev <- dev - dev[1L] ; dev[1L] <- NA
nas <- !is.na(dev)
P <- dev
P[nas] <- safe_pchisq(dev[nas], dfs[nas], lower.tail = FALSE)
aod[, c("LRT", "Pr(Chi)")] <- list(dev, P)
} else if (test == "F") {
## FIXME: allow this if denominator df are specified externally?
stop("F test STUB -- unfinished maybe forever")
dev <- ans[, 2L] - k*ans[, 1L]
dev <- dev - dev[1L] ; dev[1L] <- NA
nas <- !is.na(dev)
P <- dev
P[nas] <- safe_pchisq(dev[nas], dfs[nas], lower.tail = FALSE)
aod[, c("LRT", "Pr(F)")] <- list(dev, P)
}
}
head <- c("Single term deletions", "\nModel:", deparse(formula(object)),
if(scale > 0) paste("\nscale: ", format(scale), "\n"))
if (!is.null(method <- attr(ss,"method"))) {
head <- c(head,"Method: ",method,"\n")
}
structure(aod, heading = head, class = c("anova", "data.frame"))
}
##' @importFrom stats extractAIC
##' @S3method extractAIC merMod
extractAIC.merMod <- function(fit, scale = 0, k = 2, ...) {
L <- logLik(refitML(fit))
edf <- attr(L,"df")
c(edf,-2*L + k*edf)
}
##' @importFrom stats family
##' @S3method family merMod
family.merMod <- function(object, ...) family(object@resp, ...)
##' @S3method family glmResp
family.glmResp <- function(object, ...) {
# regenerate initialize
# expression if necessary
## FIXME: may fail with user-specified/custom family?
## should be obsolete
if(is.null(object$family$initialize))
return(do.call(object$family$family,
list(link=object$family$link)))
object$family
}
##' @S3method family lmResp
family.lmResp <- function(object, ...) gaussian()
##' @S3method family nlsResp
family.nlsResp <- function(object, ...) gaussian()
##' @importFrom stats fitted
##' @S3method fitted merMod
fitted.merMod <- function(object, ...) {
xx <- object@resp$mu
if (length(xx)==0) {
## handle 'fake' objects created by simulate()
xx <- rep(NA,nrow(model.frame(object)))
}
if (is.null(nm <- rownames(model.frame(object)))) nm <- seq_along(xx)
names(xx) <- nm
if (!is.null(fit.na.action <- attr(model.frame(object),"na.action")))
napredict(fit.na.action, xx)
else
xx
}
##' Extract the fixed-effects estimates
##'
##' Extract the estimates of the fixed-effects parameters from a fitted model.
##' @name fixef
##' @title Extract fixed-effects estimates
##' @aliases fixef fixed.effects fixef.merMod
##' @docType methods
##' @param object any fitted model object from which fixed effects estimates can
##' be extracted.
##' @param \dots optional additional arguments. Currently none are used in any
##' methods.
##' @return a named, numeric vector of fixed-effects estimates.
##' @keywords models
##' @examples
##' fixef(lmer(Reaction ~ Days + (1|Subject) + (0+Days|Subject), sleepstudy))
##' @importFrom nlme fixef
##' @export fixef
##' @method fixef merMod
##' @export
fixef.merMod <- function(object, add.dropped=FALSE, ...) {
X <- getME(object,"X")
ff <- structure(object@beta, names = dimnames(X)[[2]])
if (add.dropped) {
if (!is.null(dd <- attr(X,"col.dropped"))) {
## restore positions dropped for rank deficiency
vv <- numeric(length(ff)+length(dd))
all.pos <- seq_along(vv)
kept.pos <- all.pos[-dd]
vv[kept.pos] <- ff
names(vv)[kept.pos] <- names(ff)
vv[dd] <- NA
names(vv)[dd] <- names(dd)
ff <- vv
}
}
return(ff)
}
getFixedFormula <- function(form) {
RHSForm(form) <- nobars(RHSForm(form))
form
}
##' @importFrom stats formula
##' @S3method formula merMod
formula.merMod <- function(x, fixed.only=FALSE, random.only=FALSE, ...) {
if (missing(fixed.only) && random.only) fixed.only <- FALSE
if (fixed.only && random.only) stop("can't specify 'only fixed' and 'only random' terms")
if (is.null(form <- attr(x@frame,"formula"))) {
if (!grepl("lmer$",deparse(getCall(x)[[1]])))
stop("can't find formula stored in model frame or call")
form <- as.formula(formula(getCall(x),...))
}
if (fixed.only) {
form <- getFixedFormula(form)
}
if (random.only) {
## from predict.R
form <- reOnly(form,response=TRUE)
}
form
}
##' @S3method isREML merMod
isREML.merMod <- function(x, ...) as.logical(x@devcomp$dims[["REML"]])