-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathAnova.R
More file actions
2161 lines (2055 loc) · 85.1 KB
/
Anova.R
File metadata and controls
2161 lines (2055 loc) · 85.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#-------------------------------------------------------------------------------
# Revision history:
# 2009-01-05: bug fix in Anova_II_lm(). J. Fox
# 2009-01-16: Cox models with clusters now handled. J. Fox
# 2009-09-16: reworked glm and lm methods to handle aliased parameters. J. Fox
# 2009-09-30: renamed "Anova" to "Analysis of Deviance" in output for some methods. J. Fox
# 2009-12-22: modified Anova.mlm() to handle a user-supplied within-subject model matrix. J. Fox
# 2009-12-28: named the components of P in Anova_III_mlm(). John
# 2010-01-01: Anova_II_mlm() now hands off (again) to Anova_III_mlm() when there
# is only an intercept in the between-subjects model
# 2010-02-17: Fixed bug that caused some models with aliased coefficients to fail. J. Fox
# 2010-06-14: added wcrossprod and allow use of observation weights in Anova.mlm()
# 2010-06-28: Fixed Anova() tables for coxph and survreg models
# (failed because of changes in survival package.
# 2011-01-21: Added functions for mixed models. J. Fox
# 2011-01-25: Fixed Anova.polr() and Anova.multinom() to work with models with only one term. J. Fox
# 2011-05-19: local fixef() to avoid nlme/lme4 issues. J. Fox
# 2011-05-11: changed order of columns in ANOVA tables for mixed models. J. Fox
# 2011-11-27: added Anova.svyglm(). J. Fox
# 2011-12-31: fixed bug in Anova.II(and III).F.glm() when na.exclude used. J. Fox
# 2012-02-28: added test.statistic argument to Anova.mer(). J.Fox
# 2012-03-02: fixed test abbreviation of test.statistic argument to Anova.default()
# called by other Anova() methods. J. Fox
# 2013-06-17: modified summary.Anova.mlm(), introduced print.summary.Anova.mlm(),
# adapting code contributed by Gabriel Baud-Bovy. J. Fox
# 2013-06-20: added Anova.merMod() method. J. Fox
# 2013-06-22: tweaks to local fixef(). J. Fox
# 2013-06-22: test argument uniformly uses "Chisq" rather than "chisq". J. Fox
# 2013-08-19: replaced calls to print.anova(). J. Fox
# 2014-08-17: added calls to requireNamespace() and :: where needed (doesn't work for pbkrtest). J. Fox
# 2014-08-18: fixed bugs in Anova.survreg() for types II, III LR tests and Wald tests. J. Fox
# 2014-09-23: added Anova.rlm(). J. Fox
# 2014-10-10: removed MASS:: from calls to polr(). John
# 2014-12-18: check that residual df and SS are nonzero in Anova.lm(). John
# 2015-01-27: vcovAdj() and methods now imported from pbkrtest. John
# 2015-02-18: force evaluation of vcov. when it's a function. John
# 2015-04-30: don't allow error.estimate="dispersion" for F-tests in binomial
# and Poission GLMs. John
# 2015-08-29: fixed Anova() for coxph models with clusters. John
# 2015-09-04: added support for coxme models. John
# 2015-09-11: modified Anova.default() to work with vglm objects from VGAM. John
# 2015-09-15: fixed Anova.default() so that F-tests work again. John
# 2015-11-13: modify Anova.coxph() to take account of method/ties argument. John
# 2016-06-03: added SSP and SSPE args to print.summary.Anova.mlm(). John
# 2016-06-25: added code to optionally print univariate ANOVAs for a mlm. John
# 2017-02-16: replace polr() calls with MASS::polr(), multinom() with nnet::multinom(),
# vcovAdj() with pbkrtest::vcovAdj(). John
# 2017-03-08: fixed bug in print.summary.Anova.mlm(). John
# 2017-11-07: added complete=FALSE to vcov() and vcov.() calls. John
# 2017-11-24: small improvements to output. John
# 2017-11-29: further fixed to vcov() and vcov.() calls. John
# 2018-01-15: Anova.multinom() now works with response matrix. JF
# 2018-02-11: If there are aliased coefs in lm object, treat as GLM. JF
# 2018-04-04: pass ... arguments through print() methods. Follows comments by Egor Katkov. JF
# 2019-10-16: modify Anova.coxph() and Anova.default() for coxph() models with strata (or clusters)
# (following problem reported by Susan Galloway Hilsenbeck). JF
# 2019-02-17: fix Anova.lme() to work with models without intercepts (to fix bug reported by Benjamin Tyner). JF
# 2020-04-01: fix Anova.coxph() to work with weights (to fix bug reported by Daniel Morillo Cuadrado)
# 2020-05-27: tweak to handling of Anova.coxph Wald tests. JF
# 2020-12-07: Standardize handling of vcov. arg
# 2020-12-18: fix Anova.lme() so that it handles missing factor levels. JF
# 2020-12-18: make assignVector() generic; add default and svyolr methods;
# add unexported svyolr methods for coef() and vcov();
# all this to make Anova() and linearHypothesis() work with svyolr. JF
# 2021-04-07: fix Anova.lm() so that SSs are computed when vcov. not specified. JF
# 2021-06-12: vcov. arg. now works for mer models.
# 2021-06-14: further fixes to vcov. arg for Anova.mer(). JF
# introduced vcov. arg to Anova.glm(). JF
# 2021-06-16: Fix imatrix arg to Anova.mlm() (contribution of Benedikt Langenberg).JF
# 2021-06-19: make sure that calls to anova() for survival::survreg() models return "anova" objects. JF
# 2022-01-17,18: handle singularities better in Anova.mlm() (suggestion of Marius Barth)
# 2922-04-24: introduce new error.df argument for linearHypothesis.default(). JF
# 2022-06-07: Added Anova.svycoxph(). JF
# 2022-07-22: Fix bug in Anova.survreg() for Wald tests (reported by Megan Taylor Jones). JF
# 2022-07-22: Make Anova.lm() more robust when there are aliased coefficients (following report by Taiwo Fagbohungbe). JF
# 2022-07-27: Tweaked the last fix so the tolerance for deciding rank is the same for the lm model and the temporary glm model. SW
# 2023-10-03: Suppress LR tests for "coxph" models using the tt argument (following bug report by Ken Beath). JF
# 2024-05-08: Added Anova.clm() and Anova.clmm() methods (and supporting functions) (following report by Karl Ove Hufthammer). JF
# 2024-05-14: Rename internal functions to replace .s with _s. JF
# 2024-09-19: model.matrix.lme() now handles contrasts and xlev correctly, fixing a bug in Anova.lme() (reported by Ben Bolker). JF
#-------------------------------------------------------------------------------
# Type II and III tests for linear, generalized linear, and other models (J. Fox)
ConjComp <- function(X, Z = diag( nrow(X)), ip = diag(nrow(X))) {
# This function by Georges Monette
# finds the conjugate complement of the proj of X in span(Z) wrt
# inner product ip
# - assumes Z is of full column rank
# - projects X conjugately wrt ip into span Z
xq <- qr(t(Z) %*% ip %*% X)
if (xq$rank == 0) return(Z)
Z %*% qr.Q(xq, complete = TRUE) [ ,-(1:xq$rank)]
}
relatives <- function(term, names, factors){
is.relative <- function(term1, term2) {
all(!(factors[,term1]&(!factors[,term2])))
}
if(length(names) == 1) return(NULL)
which.term <- which(term==names)
(1:length(names))[-which.term][sapply(names[-which.term],
function(term2) is.relative(term, term2))]
}
lm2glm <- function(mod){
Data <- getModelData(mod)
wts <- weights(mod)
Data$..wts.. <- if (is.null(wts)) rep(1, nrow(Data)) else wts
form <- formula(mod)
eps <- 1000 * (if(is.null(mod$call$tol)) 1e-7 else mod$call$tol)
glm(form, weights=..wts.., data=Data, control=list(epsilon=eps))
}
globalVariables("..wts..")
Anova <- function(mod, ...){
UseMethod("Anova", mod)
}
# linear models
Anova.lm <- function(mod, error, type=c("II","III", 2, 3),
white.adjust=c(FALSE, TRUE, "hc3", "hc0", "hc1", "hc2", "hc4"),
vcov.=NULL, singular.ok, ...){
if (!is.null(vcov.)) message("Coefficient covariances computed by ", deparse(substitute(vcov.)))
if (!missing(white.adjust)) message("Coefficient covariances computed by hccm()")
if (df.residual(mod) == 0) stop("residual df = 0")
if (deviance(mod) < sqrt(.Machine$double.eps)) stop("residual sum of squares is 0 (within rounding error)")
type <- as.character(type)
white.adjust <- as.character(white.adjust)
type <- match.arg(type)
white.adjust <- match.arg(white.adjust)
if (missing(singular.ok)){
singular.ok <- type == "2" || type == "II"
}
if (has_intercept(mod) && length(coef(mod)) == 1
&& (type == "2" || type == "II")) {
type <- "III"
warning("the model contains only an intercept: Type III test substituted")
}
if (any(is.na(coef(mod))) && singular.ok){
if ((white.adjust != "FALSE") || (!is.null(vcov.)))
stop("non-standard coefficient covariance matrix\n may not be used for model with aliased coefficients")
message("Note: model has aliased coefficients\n sums of squares computed by model comparison")
result <- Anova(lm2glm(mod), type=type, singular.ok=TRUE, test.statistic="F", ...)
heading <- attributes(result)$heading
if (type == "2") type <- "II"
if (type == "3") type <- "III"
attr(result, "heading") <- c(paste("Anova Table (Type", type, "tests)"), "", heading[2])
return(result)
}
if (white.adjust != "FALSE"){
if (white.adjust == "TRUE") white.adjust <- "hc3"
return(Anova.default(mod, type=type, vcov.=hccm(mod, type=white.adjust), test.statistic="F",
singular.ok=singular.ok, ...))
}
else if (!is.null(vcov.)) return(Anova.default(mod, type=type, vcov.=vcov., test.statistic="F",
singular.ok=singular.ok, ...))
switch(type,
II=Anova_II_lm(mod, error, singular.ok=singular.ok, ...),
III=Anova_III_lm(mod, error, singular.ok=singular.ok, ...),
"2"=Anova_II_lm(mod, error, singular.ok=singular.ok, ...),
"3"=Anova_III_lm(mod, error, singular.ok=singular.ok,...))
}
Anova.aov <- function(mod, ...){
class(mod) <- "lm"
Anova.lm(mod, ...)
}
Anova_II_lm <- function(mod, error, singular.ok=TRUE, ...){
if (!missing(error)){
sumry <- summary(error, corr=FALSE)
s2 <- sumry$sigma^2
error.df <- error$df.residual
error.SS <- s2*error.df
}
SS.term <- function(term){
which.term <- which(term == names)
subs.term <- which(assign == which.term)
relatives <- relatives(term, names, fac)
subs.relatives <- NULL
for (relative in relatives)
subs.relatives <- c(subs.relatives, which(assign == relative))
hyp.matrix.1 <- I.p[subs.relatives,,drop=FALSE]
hyp.matrix.1 <- hyp.matrix.1[, not.aliased, drop=FALSE]
hyp.matrix.2 <- I.p[c(subs.relatives,subs.term),,drop=FALSE]
hyp.matrix.2 <- hyp.matrix.2[, not.aliased, drop=FALSE]
hyp.matrix.term <- if (nrow(hyp.matrix.1) == 0) hyp.matrix.2
else t(ConjComp(t(hyp.matrix.1), t(hyp.matrix.2), vcov(mod, complete=FALSE)))
hyp.matrix.term <- hyp.matrix.term[!apply(hyp.matrix.term, 1,
function(x) all(x == 0)), , drop=FALSE]
if (nrow(hyp.matrix.term) == 0)
return(c(SS=NA, df=0))
lh <- linearHypothesis(mod, hyp.matrix.term,
singular.ok=singular.ok, ...)
abs(c(SS=lh$"Sum of Sq"[2], df=lh$Df[2]))
}
not.aliased <- !is.na(coef(mod))
if (!singular.ok && !all(not.aliased))
stop("there are aliased coefficients in the model")
fac <- attr(terms(mod), "factors")
intercept <- has_intercept(mod)
I.p <- diag(length(coefficients(mod)))
assign <- mod$assign
assign[!not.aliased] <- NA
names <- term.names(mod)
if (intercept) names <-names[-1]
n.terms <- length(names)
p <- df <- f <- SS <- rep(0, n.terms + 1)
sumry <- summary(mod, corr = FALSE)
SS[n.terms + 1] <- if (missing(error)) sumry$sigma^2*mod$df.residual
else error.SS
df[n.terms + 1] <- if (missing(error)) mod$df.residual else error.df
p[n.terms + 1] <- f[n.terms + 1] <- NA
for (i in 1:n.terms){
ss <- SS.term(names[i])
SS[i] <- ss["SS"]
df[i] <- ss["df"]
f[i] <- df[n.terms+1]*SS[i]/(df[i]*SS[n.terms + 1])
p[i] <- pf(f[i], df[i], df[n.terms + 1], lower.tail = FALSE)
}
result <- data.frame(SS, df, f, p)
row.names(result) <- c(names,"Residuals")
names(result) <- c("Sum Sq", "Df", "F value", "Pr(>F)")
class(result) <- c("anova", "data.frame")
attr(result, "heading") <- c("Anova Table (Type II tests)\n",
paste("Response:", responseName(mod)))
result
}
# type III
Anova_III_lm <- function(mod, error, singular.ok=FALSE, ...){
if (!missing(error)){
error.df <- df.residual(error)
error.SS <- deviance(error)
}
else {
error.df <- df.residual(mod)
error.SS <- deviance(mod)
}
intercept <- has_intercept(mod)
I.p <- diag(length(coefficients(mod)))
Source <- term.names(mod)
n.terms <- length(Source)
p <- df <- f <- SS <- rep(0, n.terms + 1)
assign <- mod$assign
not.aliased <- !is.na(coef(mod))
if (!singular.ok && !all(not.aliased))
stop("there are aliased coefficients in the model")
indices <- 1:n.terms
for (term in indices){
subs <- which(assign == term - intercept)
hyp.matrix <- I.p[subs,,drop=FALSE]
hyp.matrix <- hyp.matrix[, not.aliased, drop=FALSE]
hyp.matrix <- hyp.matrix[!apply(hyp.matrix, 1, function(x) all(x == 0)), , drop=FALSE]
if (nrow(hyp.matrix) == 0){
SS[term] <- NA
df[term] <- 0
f[term] <- NA
p[term] <- NA
}
else {
test <- linearHypothesis(mod, hyp.matrix, singular.ok=singular.ok, ...)
SS[term] <- test$"Sum of Sq"[2]
df[term] <- test$"Df"[2]
}
}
index.error <- n.terms + 1
Source[index.error] <- "Residuals"
SS[index.error] <- error.SS
df[index.error] <- error.df
f[indices] <- (SS[indices]/df[indices])/(error.SS/error.df)
p[indices] <- pf(f[indices], df[indices], error.df, lower.tail=FALSE)
p[index.error] <- f[index.error] <- NA
result <- data.frame(SS, df, f, p)
row.names(result) <- Source
names(result) <- c("Sum Sq", "Df", "F value", "Pr(>F)")
class(result) <- c("anova", "data.frame")
attr(result, "heading") <- c("Anova Table (Type III tests)\n", paste("Response:", responseName(mod)))
result
}
# generalized linear models
Anova.glm <- function(mod, type=c("II","III", 2, 3), test.statistic=c("LR", "Wald", "F"),
error, error.estimate=c("pearson", "dispersion", "deviance"),
vcov.=vcov(mod, complete=TRUE), singular.ok, ...){
type <- as.character(type)
type <- match.arg(type)
test.statistic <- match.arg(test.statistic)
error.estimate <- match.arg(error.estimate)
if (!missing(vcov.)) {
if (test.statistic != "Wald"){
warning(paste0('test.statistic="', test.statistic,
'"; vcov. argument ignored'))
} else {
message("Coefficient covariances computed by ", deparse(substitute(vcov.)))
}
}
vcov. <- getVcov(vcov., mod)
if (has_intercept(mod) && length(coef(mod)) == 1
&& (type == "2" || type == "II")) {
type <- "III"
warning("the model contains only an intercept: Type III test substituted")
}
if (missing(singular.ok)){
singular.ok <- type == "2" || type == "II"
}
switch(type,
II=switch(test.statistic,
LR=Anova_II_LR_glm(mod, singular.ok=singular.ok),
Wald=Anova.default(mod, type="II", singular.ok=singular.ok, vcov.=vcov.),
F=Anova_II_F_glm(mod, error, error.estimate, singular.ok=singular.ok)),
III=switch(test.statistic,
LR=Anova_III_LR_glm(mod, singular.ok=singular.ok),
Wald=Anova.default(mod, type="III", singular.ok=singular.ok, vcov.=vcov.),
F=Anova_III_F_glm(mod, error, error.estimate, singular.ok=singular.ok)),
"2"=switch(test.statistic,
LR=Anova_II_LR_glm(mod, singular.ok=singular.ok),
Wald=Anova.default(mod, type="II", singular.ok=singular.ok, vcov.=vcov.),
F=Anova_II_F_glm(mod, error, error.estimate, singular.ok=singular.ok)),
"3"=switch(test.statistic,
LR=Anova_III_LR_glm(mod, singular.ok=singular.ok),
Wald=Anova.default(mod, type="III", singular.ok=singular.ok, vcov.=vcov.),
F=Anova_III_F_glm(mod, error, error.estimate, singular.ok=singular.ok)))
}
# type III
# LR test
Anova_III_LR_glm <- function(mod, singular.ok=FALSE, ...){
if (!singular.ok && any(is.na(coef(mod))))
stop("there are aliased coefficients in the model")
Source <- if (has_intercept(mod)) term.names(mod)[-1]
else term.names(mod)
n.terms <- length(Source)
p <- df <- LR <- rep(0, n.terms)
dispersion <- summary(mod, corr = FALSE)$dispersion
deviance <- deviance(mod)/dispersion
for (term in 1:n.terms){
mod.1 <- drop1(mod, scope=eval(parse(text=paste("~",Source[term]))))
df[term] <- mod.1$Df[2]
LR[term] <- if (df[term] == 0) NA else (mod.1$Deviance[2]/dispersion)-deviance
p[term] <- pchisq(LR[term], df[term], lower.tail = FALSE)
}
result <- data.frame(LR, df, p)
row.names(result) <- Source
names(result) <- c("LR Chisq", "Df", "Pr(>Chisq)")
class(result) <- c("anova","data.frame")
attr(result, "heading") <- c("Analysis of Deviance Table (Type III tests)\n", paste("Response:", responseName(mod)))
result
}
# F test
Anova_III_F_glm <- function(mod, error, error.estimate, singular.ok=FALSE, ...){
if (!singular.ok && any(is.na(coef(mod))))
stop("there are aliased coefficients in the model")
fam <- family(mod)$family
if ((fam == "binomial" || fam == "poisson") && error.estimate == "dispersion"){
warning("dispersion parameter estimated from the Pearson residuals, not taken as 1")
error.estimate <- "pearson"
}
if (missing(error)) error <- mod
df.res <- df.residual(error)
error.SS <- switch(error.estimate,
pearson=sum(residuals(error, "pearson")^2, na.rm=TRUE),
dispersion=df.res*summary(error, corr = FALSE)$dispersion,
deviance=deviance(error))
Source <- if (has_intercept(mod)) term.names(mod)[-1]
else term.names(mod)
n.terms <- length(Source)
p <- df <- f <- SS <-rep(0, n.terms+1)
f[n.terms+1] <- p[n.terms+1] <- NA
df[n.terms+1] <- df.res
SS[n.terms+1] <- error.SS
dispersion <- error.SS/df.res
deviance <- deviance(mod)
for (term in 1:n.terms){
mod.1 <- drop1(mod, scope=eval(parse(text=paste("~",Source[term]))))
df[term] <- mod.1$Df[2]
SS[term] <- mod.1$Deviance[2] - deviance
f[term] <- if (df[term] == 0) NA else (SS[term]/df[term])/dispersion
p[term] <- pf(f[term], df[term], df.res, lower.tail = FALSE)
}
result <- data.frame(SS, df, f, p)
row.names(result) <- c(Source, "Residuals")
names(result) <- c("Sum Sq", "Df", "F values", "Pr(>F)")
class(result) <- c("anova","data.frame")
attr(result, "heading") <- c("Analysis of Deviance Table (Type III tests)\n",
paste("Response:", responseName(mod)),
paste("Error estimate based on",
switch(error.estimate,
pearson="Pearson residuals", dispersion="estimated dispersion",
deviance="deviance"), "\n"))
result
}
# type II
# LR test
Anova_II_LR_glm <- function(mod, singular.ok=TRUE, ...){
if (!singular.ok && any(is.na(coef(mod))))
stop("there are aliased coefficients in the model")
# (some code adapted from drop1.glm)
which.nms <- function(name) which(asgn == which(names == name))
fac <- attr(terms(mod), "factors")
names <- if (has_intercept(mod)) term.names(mod)[-1]
else term.names(mod)
n.terms <- length(names)
X <- model.matrix(mod)
y <- mod$y
if (is.null(y)) y <- model.response(model.frame(mod), "numeric")
wt <- mod$prior.weights
if (is.null(wt)) wt <- rep(1, length(y))
asgn <- attr(X, 'assign')
df <- p <- LR <- rep(0, n.terms)
dispersion <- summary(mod, corr = FALSE)$dispersion
for (term in 1:n.terms){
rels <- names[relatives(names[term], names, fac)]
exclude.1 <- as.vector(unlist(sapply(c(names[term], rels), which.nms)))
mod.1 <- glm.fit(X[, -exclude.1, drop = FALSE], y, wt, offset = mod$offset,
family = mod$family, control = mod$control)
dev.1 <- deviance(mod.1)
mod.2 <- if (length(rels) == 0) mod
else {
exclude.2 <- as.vector(unlist(sapply(rels, which.nms)))
glm.fit(X[, -exclude.2, drop = FALSE], y, wt, offset = mod$offset,
family = mod$family, control = mod$control)
}
dev.2 <- deviance(mod.2)
df[term] <- df.residual(mod.1) - df.residual(mod.2)
if (df[term] == 0) LR[term] <- p[term] <- NA
else {
LR[term] <- (dev.1 - dev.2)/dispersion
p[term] <- pchisq(LR[term], df[term], lower.tail=FALSE)
}
}
result <- data.frame(LR, df, p)
row.names(result) <- names
names(result) <- c("LR Chisq", "Df", "Pr(>Chisq)")
class(result) <- c("anova", "data.frame")
attr(result, "heading") <-
c("Analysis of Deviance Table (Type II tests)\n", paste("Response:", responseName(mod)))
result
}
# F test
Anova_II_F_glm <- function(mod, error, error.estimate, singular.ok=TRUE, ...){
# (some code adapted from drop1.glm)
if (!singular.ok && any(is.na(coef(mod))))
stop("there are aliased coefficients in the model")
fam <- family(mod)$family
if ((fam == "binomial" || fam == "poisson") && error.estimate == "dispersion"){
warning("dispersion parameter estimated from the Pearson residuals, not taken as 1")
error.estimate <- "pearson"
}
which.nms <- function(name) which(asgn == which(names == name))
if (missing(error)) error <- mod
df.res <- df.residual(error)
error.SS <- switch(error.estimate,
pearson = sum(residuals(error, "pearson")^2, na.rm=TRUE),
dispersion = df.res*summary(error, corr = FALSE)$dispersion,
deviance = deviance(error))
fac <- attr(terms(mod), "factors")
names <- if (has_intercept(mod)) term.names(mod)[-1]
else term.names(mod)
n.terms <- length(names)
X <- model.matrix(mod)
y <- mod$y
if (is.null(y)) y <- model.response(model.frame(mod), "numeric")
wt <- mod$prior.weights
if (is.null(wt)) wt <- rep(1, length(y))
asgn <- attr(X, 'assign')
p <- df <- f <- SS <- rep(0, n.terms+1)
f[n.terms+1] <- p[n.terms+1] <- NA
df[n.terms+1] <- df.res
SS[n.terms+1] <- error.SS
dispersion <- error.SS/df.res
for (term in 1:n.terms){
rels <- names[relatives(names[term], names, fac)]
exclude.1 <- as.vector(unlist(sapply(c(names[term], rels), which.nms)))
mod.1 <- glm.fit(X[, -exclude.1, drop = FALSE], y, wt, offset = mod$offset,
family = mod$family, control = mod$control)
dev.1 <- deviance(mod.1)
mod.2 <- if (length(rels) == 0) mod
else {
exclude.2 <- as.vector(unlist(sapply(rels, which.nms)))
glm.fit(X[, -exclude.2, drop = FALSE], y, wt, offset = mod$offset,
family = mod$family, control = mod$control)
}
dev.2 <- deviance(mod.2)
df[term] <- df.residual(mod.1) - df.residual(mod.2)
if (df[term] == 0) SS[term] <- f[term] <- p[term] <- NA
else {
SS[term] <- dev.1 - dev.2
f[term] <- SS[term]/(dispersion*df[term])
p[term] <- pf(f[term], df[term], df.res, lower.tail=FALSE)
}
}
result <- data.frame(SS, df, f, p)
row.names(result) <- c(names, "Residuals")
names(result) <- c("Sum Sq", "Df", "F value", "Pr(>F)")
class(result) <- c("anova", "data.frame")
attr(result, "heading") <- c("Analysis of Deviance Table (Type II tests)\n",
paste("Response:", responseName(mod)),
paste("Error estimate based on",
switch(error.estimate,
pearson="Pearson residuals",
dispersion="estimated dispersion",
deviance="deviance"), "\n"))
result
}
# multinomial logit models (via multinom in the nnet package)
Anova.multinom <-
function (mod, type = c("II", "III", 2, 3), ...)
{
type <- as.character(type)
type <- match.arg(type)
if (has_intercept(mod) && length(coef(mod)) == 1
&& (type == "2" || type == "II")) {
type <- "III"
warning("the model contains only an intercept: Type III test substituted")
}
switch(type,
II = Anova_II_multinom(mod, ...),
III = Anova_III_multinom(mod, ...),
"2" = Anova_II_multinom(mod, ...),
"3" = Anova_III_multinom(mod, ...))
}
Anova_II_multinom <- function (mod, ...)
{
which.nms <- function(name) which(asgn == which(names ==
name))
fac <- attr(terms(mod), "factors")
names <- if (has_intercept(mod)) term.names(mod)[-1]
else term.names(mod)
n.terms <- length(names)
X <- model.matrix(mod)
y <- model.response(model.frame(mod))
wt <- if (is.matrix(y)) rep(1, nrow(y)) else mod$weights
asgn <- attr(X, "assign")
p <- LR <- rep(0, n.terms)
df <- df.terms(mod)
for (term in 1:n.terms) {
rels <- names[relatives(names[term], names, fac)]
exclude.1 <- as.vector(unlist(sapply(c(names[term], rels),
which.nms)))
mod.1 <-if (n.terms > 1) nnet::multinom(y ~ X[, -c(1, exclude.1)], weights=wt, trace=FALSE)
else nnet::multinom(y ~ 1, weights=wt, race=FALSE)
dev.1 <- deviance(mod.1)
mod.2 <- if (length(rels) == 0)
mod
else {
exclude.2 <- as.vector(unlist(sapply(rels, which.nms)))
nnet::multinom(y ~ X[, -c(1, exclude.2)], weights=wt, trace=FALSE)
}
dev.2 <- deviance(mod.2)
LR[term] <- dev.1 - dev.2
p[term] <- pchisq(LR[term], df[term], lower.tail=FALSE)
}
result <- data.frame(LR, df, p)
row.names(result) <- names
names(result) <- c("LR Chisq", "Df", "Pr(>Chisq)")
class(result) <- c("anova", "data.frame")
attr(result, "heading") <- c("Analysis of Deviance Table (Type II tests)\n",
paste("Response:", responseName(mod)))
result
}
Anova_III_multinom <- function (mod, ...)
{
names <- if (has_intercept(mod)) term.names(mod)[-1]
else term.names(mod)
n.terms <- length(names)
X <- model.matrix(mod)
y <- model.response(model.frame(mod))
wt <- if (is.matrix(y)) rep(1, nrow(y)) else mod$weights
asgn <- attr(X, "assign")
p <- LR <- rep(0, n.terms)
df <- df.terms(mod)
deviance <- deviance(mod)
for (term in 1:n.terms) {
mod.1 <- if (n.terms > 1) nnet::multinom(y ~ X[, term != asgn][, -1], weights=wt, trace=FALSE)
else nnet::multinom(y ~ 1, weights=wt, trace=FALSE)
LR[term] <- deviance(mod.1) - deviance
p[term] <- pchisq(LR[term], df[term], lower.tail=FALSE)
}
result <- data.frame(LR, df, p)
row.names(result) <- names
names(result) <- c("LR Chisq", "Df", "Pr(>Chisq)")
class(result) <- c("anova", "data.frame")
attr(result, "heading") <- c("Analysis of Deviance Table (Type III tests)\n",
paste("Response:", responseName(mod)))
result
}
# proportional-odds logit models (via polr in the MASS package)
Anova.polr <- function (mod, type = c("II", "III", 2, 3), ...)
{
type <- as.character(type)
type <- match.arg(type)
if (has_intercept(mod) && length(coef(mod)) == 1
&& (type == "2" || type == "II")) {
type <- "III"
warning("the model contains only an intercept: Type III test substituted")
}
switch(type,
II = Anova_II_polr(mod, ...),
III = Anova_III_polr(mod, ...),
"2" = Anova_II_polr(mod, ...),
"3" = Anova_III_polr(mod, ...))
}
Anova_II_polr <- function (mod, ...)
{
if (!requireNamespace("MASS")) stop("MASS package is missing")
which.nms <- function(name) which(asgn == which(names ==
name))
fac <- attr(terms(mod), "factors")
names <- term.names(mod)
n.terms <- length(names)
X <- model.matrix(mod)
y <- model.response(model.frame(mod))
wt <- model.weights(model.frame(mod))
asgn <- attr(X, "assign")
p <- LR <- rep(0, n.terms)
df <- df.terms(mod)
for (term in 1:n.terms) {
rels <- names[relatives(names[term], names, fac)]
exclude.1 <- as.vector(unlist(sapply(c(names[term], rels),
which.nms)))
mod.1 <- if (n.terms > 1) MASS::polr(y ~ X[, -c(1, exclude.1)], weights=wt)
else MASS::polr(y ~ 1, weights=wt)
dev.1 <- deviance(mod.1)
mod.2 <- if (length(rels) == 0)
mod
else {
exclude.2 <- as.vector(unlist(sapply(rels, which.nms)))
MASS::polr(y ~ X[, -c(1, exclude.2)], weights=wt)
}
dev.2 <- deviance(mod.2)
LR[term] <- dev.1 - dev.2
p[term] <- pchisq(LR[term], df[term], lower.tail=FALSE)
}
result <- data.frame(LR, df, p)
row.names(result) <- names
names(result) <- c("LR Chisq", "Df", "Pr(>Chisq)")
class(result) <- c("anova", "data.frame")
attr(result, "heading") <- c("Analysis of Deviance Table (Type II tests)\n",
paste("Response:", responseName(mod)))
result
}
Anova_III_polr <- function (mod, ...)
{
if (!requireNamespace("MASS")) stop("MASS package is missing")
names <- term.names(mod)
n.terms <- length(names)
X <- model.matrix(mod)
y <- model.response(model.frame(mod))
wt <- model.weights(model.frame(mod))
asgn <- attr(X, "assign")
p <- LR <- rep(0, n.terms)
df <- df.terms(mod)
deviance <- deviance(mod)
for (term in 1:n.terms) {
mod.1 <- if (n.terms > 1) MASS::polr(y ~ X[, term != asgn][, -1], weights=wt)
else MASS::polr(y ~ 1, weights=wt)
LR[term] <- deviance(mod.1) - deviance
p[term] <- pchisq(LR[term], df[term], lower.tail=FALSE)
}
result <- data.frame(LR, df, p)
row.names(result) <- names
names(result) <- c("LR Chisq", "Df", "Pr(>Chisq)")
class(result) <- c("anova", "data.frame")
attr(result, "heading") <- c("Analysis of Deviance Table (Type III tests)\n",
paste("Response:", responseName(mod)))
result
}
# multivariate linear models
# the following 3 functions copied from the stats package (not exported from stats)
Pillai <- function (eig, q, df.res) {
test <- sum(eig/(1 + eig))
p <- length(eig)
s <- min(p, q)
n <- 0.5 * (df.res - p - 1)
m <- 0.5 * (abs(p - q) - 1)
tmp1 <- 2 * m + s + 1
tmp2 <- 2 * n + s + 1
c(test, (tmp2/tmp1 * test)/(s - test), s * tmp1, s * tmp2)
}
Wilks <- function (eig, q, df.res) {
test <- prod(1/(1 + eig))
p <- length(eig)
tmp1 <- df.res - 0.5 * (p - q + 1)
tmp2 <- (p * q - 2)/4
tmp3 <- p^2 + q^2 - 5
tmp3 <- if (tmp3 > 0)
sqrt(((p * q)^2 - 4)/tmp3)
else 1
c(test, ((test^(-1/tmp3) - 1) * (tmp1 * tmp3 - 2 * tmp2))/p/q,
p * q, tmp1 * tmp3 - 2 * tmp2)
}
HL <- function (eig, q, df.res) {
test <- sum(eig)
p <- length(eig)
m <- 0.5 * (abs(p - q) - 1)
n <- 0.5 * (df.res - p - 1)
s <- min(p, q)
tmp1 <- 2 * m + s + 1
tmp2 <- 2 * (s * n + 1)
c(test, (tmp2 * test)/s/s/tmp1, s * tmp1, tmp2)
}
Roy <- function (eig, q, df.res) {
p <- length(eig)
test <- max(eig)
tmp1 <- max(p, q)
tmp2 <- df.res - tmp1 + q
c(test, (tmp2 * test)/tmp1, tmp1, tmp2)
}
has_intercept.mlm <- function (model, ...)
any(row.names(coefficients(model)) == "(Intercept)")
Anova.mlm <- function(mod, type=c("II","III", 2, 3), SSPE, error.df, idata,
idesign, icontrasts=c("contr.sum", "contr.poly"), imatrix,
test.statistic=c("Pillai", "Wilks", "Hotelling-Lawley", "Roy"),...){
if (any(is.na(coef(mod))))
stop(if(!missing(idata)) "between-subjects ", "model is singular")
wts <- if (!is.null(mod$weights)) mod$weights else rep(1, nrow(model.matrix(mod)))
type <- as.character(type)
type <- match.arg(type)
test.statistic <- match.arg(test.statistic)
if (missing(SSPE)) SSPE <- wcrossprod(residuals(mod), w=wts)
if (missing(idata)) {
idata <- NULL
idesign <- NULL
}
if (missing(imatrix)) imatrix <- NULL
error.df <- if (missing(error.df)) df.residual(mod)
else error.df
switch(type,
II=Anova_II_mlm(mod, SSPE, error.df, idata, idesign, icontrasts, imatrix, test.statistic, ...),
III=Anova_III_mlm(mod, SSPE, error.df, idata, idesign, icontrasts, imatrix, test.statistic, ...),
"2"=Anova_II_mlm(mod, SSPE, error.df, idata, idesign, icontrasts, imatrix, test.statistic, ...),
"3"=Anova_III_mlm(mod, SSPE, error.df, idata, idesign, icontrasts, imatrix, test.statistic, ...))
}
Anova_III_mlm <- function(mod, SSPE, error.df, idata, idesign, icontrasts, imatrix, test, ...){
intercept <- has_intercept(mod)
p <- nrow(coefficients(mod))
I.p <- diag(p)
terms <- term.names(mod)
n.terms <- length(terms)
assign <- mod$assign
if (is.null(idata) && is.null(imatrix)){
if ((n.terms == 0) && intercept) {
Test <- linearHypothesis(mod, 1, SSPE=SSPE, ...)
result <- list(SSP=Test$SSPH, SSPE=SSPE, df=1, error.df=error.df,
terms="(Intercept)", repeated=FALSE, type="III", test=test)
class(result) <- "Anova.mlm"
return(result)
}
SSP <- as.list(rep(0, n.terms))
df <- rep(0, n.terms)
names(df) <- names(SSP) <- terms
for (term in 1:n.terms){
subs <- which(assign == term - intercept)
hyp.matrix <- I.p[subs,,drop=FALSE]
Test <- linearHypothesis(mod, hyp.matrix, SSPE=SSPE, ...)
SSP[[term]] <- Test$SSPH
df[term]<- length(subs)
}
result <- list(SSP=SSP, SSPE=SSPE, df=df, error.df=error.df, terms=terms,
repeated=FALSE, type="III", test=test)
}
else {
if (!is.null(imatrix)){
X.design <- do.call(cbind, imatrix)
ncols <- sapply(imatrix, ncol)
end <- cumsum(ncols)
start <- c(1, (end + 1))[-(length(end) + 1)]
cols <- mapply(seq, from=start, to=end)
iterms <- names(end)
names(cols) <- iterms
itrms <- unlist(sapply(1:length(imatrix), function(x) replicate(ncol(imatrix[[x]]), x-1)))
check.imatrix(X.design, itrms)
}
else {
if (is.null(idesign)) stop("idesign (intra-subject design) missing.")
for (i in 1:length(idata)){
if (is.null(attr(idata[,i], "contrasts"))){
contrasts(idata[,i]) <- if (is.ordered(idata[,i])) icontrasts[2]
else icontrasts[1]
}
}
X.design <- model.matrix(idesign, data=idata)
i.intercept <- has_intercept(X.design)
iterms <- term.names(idesign)
if (i.intercept) iterms <- c("(Intercept)", iterms)
check.imatrix(X.design)
}
n.tests <- n.terms*length(iterms)
df <- rep(0, n.tests)
singular <- rep(FALSE, n.tests)
hnames <- rep("", n.tests)
P <- SSPEH <- SSP <- as.list(df)
i <- 0
for (iterm in iterms){
for (term in 1:n.terms){
subs <- which(assign == term - intercept)
hyp.matrix <- I.p[subs,,drop=FALSE]
i <- i + 1
Test <- linearHypothesis(mod, hyp.matrix, SSPE=SSPE,
idata=idata, idesign=idesign, icontrasts=icontrasts, iterms=iterm,
check.imatrix=FALSE, P=imatrix[[iterm]], singular.ok=TRUE, ...)
SSP[[i]] <- Test$SSPH
SSPEH[[i]] <- Test$SSPE
P[[i]] <- Test$P
df[i] <- length(subs)
hnames[i] <- if (iterm == "(Intercept)") terms[term]
else if (terms[term] == "(Intercept)") iterm
else paste(terms[term], ":", iterm, sep="")
singular[i] <- Test$singular
}
}
names(singular) <- names(df) <- names(SSP) <- names(SSPEH) <- names(P) <- hnames
result <- list(SSP=SSP, SSPE=SSPEH, P=P, df=df, error.df=error.df,
terms=hnames, repeated=TRUE, type="III", test=test,
idata=idata, idesign=idesign, icontrasts=icontrasts, imatrix=imatrix,
singular=singular)
}
class(result) <- "Anova.mlm"
result
}
Anova_II_mlm <- function(mod, SSPE, error.df, idata, idesign, icontrasts, imatrix, test, ...){
wts <- if (!is.null(mod$weights)) mod$weights else rep(1, nrow(model.matrix(mod)))
V <- solve(wcrossprod(model.matrix(mod), w=wts))
SSP.term <- function(term, iterm){
which.term <- which(term == terms)
subs.term <- which(assign == which.term)
relatives <- relatives(term, terms, fac)
subs.relatives <- NULL
for (relative in relatives) subs.relatives <- c(subs.relatives, which(assign==relative))
hyp.matrix.1 <- I.p[subs.relatives,,drop=FALSE]
hyp.matrix.2 <- I.p[c(subs.relatives, subs.term),,drop=FALSE]
if (missing(iterm)){
SSP1 <- if (length(subs.relatives) == 0) 0
else linearHypothesis(mod, hyp.matrix.1, SSPE=SSPE, V=V, singular.ok=TRUE, ...)$SSPH
SSP2 <- linearHypothesis(mod, hyp.matrix.2, SSPE=SSPE, V=V, singular.ok=TRUE, ...)$SSPH
return(SSP2 - SSP1)
}
else {
SSP1 <- if (length(subs.relatives) == 0) 0
else linearHypothesis(mod, hyp.matrix.1, SSPE=SSPE, V=V,
idata=idata, idesign=idesign, iterms=iterm, icontrasts=icontrasts, P=imatrix[[iterm]], singular.ok=TRUE, ...)$SSPH
lh2 <- linearHypothesis(mod, hyp.matrix.2, SSPE=SSPE, V=V,
idata=idata, idesign=idesign, iterms=iterm, icontrasts=icontrasts, P=imatrix[[iterm]], singular.ok=TRUE, ...)
return(list(SSP = lh2$SSPH - SSP1, SSPE=lh2$SSPE, P=lh2$P, singular=lh2$singular))
}
}
fac <- attr(terms(mod), "factors")
intercept <- has_intercept(mod)
p <- nrow(coefficients(mod))
I.p <- diag(p)
assign <- mod$assign
terms <- term.names(mod)
if (intercept) terms <- terms[-1]
n.terms <- length(terms)
if (n.terms == 0){
message("Note: model has only an intercept; equivalent type-III tests substituted.")
return(Anova_III_mlm(mod, SSPE, error.df, idata, idesign, icontrasts, imatrix, test, ...))
}
if (is.null(idata) && is.null(imatrix)){
SSP <- as.list(rep(0, n.terms))
df <- rep(0, n.terms)
names(df) <- names(SSP) <- terms
for (i in 1:n.terms){
SSP[[i]] <- SSP.term(terms[i])
df[i]<- df.terms(mod, terms[i])
}
result <- list(SSP=SSP, SSPE=SSPE, df=df, error.df=error.df, terms=terms,
repeated=FALSE, type="II", test=test)
}
else {
if (!is.null(imatrix)){
X.design <- do.call(cbind, imatrix)
ncols <- sapply(imatrix, ncol)
end <- cumsum(ncols)
start <- c(1, (end + 1))[-(length(end) + 1)]
cols <- mapply(seq, from=start, to=end)
iterms <- names(end)
names(cols) <- iterms
itrms <- unlist(sapply(1:length(imatrix), function(x) replicate(ncol(imatrix[[x]]), x-1)))
check.imatrix(X.design, itrms)
}
else {
if (is.null(idesign)) stop("idesign (intra-subject design) missing.")
for (i in 1:length(idata)){
if (is.null(attr(idata[,i], "contrasts"))){
contrasts(idata[,i]) <- if (is.ordered(idata[,i])) icontrasts[2]
else icontrasts[1]
}
}
X.design <- model.matrix(idesign, data=idata)
iintercept <- has_intercept(X.design)
iterms <- term.names(idesign)
if (iintercept) iterms <- c("(Intercept)", iterms)
check.imatrix(X.design)
}
n.tests <-(n.terms + intercept)*length(iterms)
df <- rep(0, n.tests)
singular <- rep(FALSE, n.tests)
hnames <- rep("", length(df))
P <- SSPEH <- SSP <- as.list(df)
i <- 0
for (iterm in iterms){
if (intercept){
i <- i + 1
hyp.matrix.1 <- I.p[-1,,drop=FALSE]
SSP1 <- linearHypothesis(mod, hyp.matrix.1, SSPE=SSPE, V=V,
idata=idata, idesign=idesign, iterms=iterm, icontrasts=icontrasts,
check.imatrix=FALSE, P=imatrix[[iterm]], singular.ok=TRUE, ...)$SSPH
lh2 <- linearHypothesis(mod, I.p, SSPE=SSPE, V=V,
idata=idata, idesign=idesign, iterms=iterm, icontrasts=icontrasts,
check.imatrix=FALSE, P=imatrix[[iterm]], singular.ok=TRUE, ...)
SSP[[i]] <- lh2$SSPH - SSP1
SSPEH[[i]] <- lh2$SSPE
P[[i]] <- lh2$P
singular[i] <- lh2$singular
df[i] <- 1
hnames[i] <- iterm
}
for (term in 1:n.terms){
subs <- which(assign == term)
i <- i + 1
Test <- SSP.term(terms[term], iterm)
SSP[[i]] <- Test$SSP
SSPEH[[i]] <- Test$SSPE
P[[i]] <- Test$P
singular[i] <- Test$singular
df[i]<- length(subs)
hnames[i] <- if (iterm == "(Intercept)") terms[term]
else paste(terms[term], ":", iterm, sep="")
}
}
names(singular) <- names(df) <- names(P) <- names(SSP) <- names(SSPEH) <- hnames
result <- list(SSP=SSP, SSPE=SSPEH, P=P, df=df, error.df=error.df,
terms=hnames, repeated=TRUE, type="II", test=test,
idata=idata, idesign=idesign, icontrasts=icontrasts, imatrix=imatrix,
singular=singular)
}
class(result) <- "Anova.mlm"
result
}
print.Anova.mlm <- function(x, ...){
if ((!is.null(x$singular)) && any(x$singular)) stop("singular error SSP matrix; multivariate tests unavailable\ntry summary(object, multivariate=FALSE)")
test <- x$test
repeated <- x$repeated
ntests <- length(x$terms)
tests <- matrix(NA, ntests, 4)
if (!repeated) SSPE.qr <- qr(x$SSPE)
for (term in 1:ntests){
# some of the code here adapted from stats:::summary.manova
eigs <- Re(eigen(qr.coef(if (repeated) qr(x$SSPE[[term]]) else SSPE.qr,
x$SSP[[term]]), symmetric = FALSE)$values)
tests[term, 1:4] <- switch(test,
Pillai = Pillai(eigs, x$df[term], x$error.df),
Wilks = Wilks(eigs, x$df[term], x$error.df),
"Hotelling-Lawley" = HL(eigs, x$df[term], x$error.df),
Roy = Roy(eigs, x$df[term], x$error.df))
}
ok <- tests[, 2] >= 0 & tests[, 3] > 0 & tests[, 4] > 0
ok <- !is.na(ok) & ok
tests <- cbind(x$df, tests, pf(tests[ok, 2], tests[ok, 3], tests[ok, 4],
lower.tail = FALSE))
rownames(tests) <- x$terms