/
plot_summary_print.R
789 lines (774 loc) · 29.8 KB
/
plot_summary_print.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
# ============================== plot.chandwich ===============================
#' Plot diagnostics for a chandwich object
#'
#' \code{plot} method for class "chandwich". Only applicable to an object
#' \code{x} for which \code{attr(x, "p_current") = 1}, i.e. a model with
#' one free parameter.
#'
#' @param x an object of class "chandwich", a result of a call to
#' \code{\link{adjust_loglik}}.
#' @param y Not used.
#' @param type An integer vector, a subset of the numbers \code{1:4}.
#' Indicates which loglikelihoods to plot: \code{1} for \code{"vertical"}
#' adjustment; \code{2} for \code{"cholesky"} (horizontal adjustment);
#' \code{3} for \code{"spectral"} (horizontal adjustment); \code{4}
#' for no adjustment, i.e. based on the independence loglikelihood.
#' @param legend A logical scalar or a character vector. If this is
#' supplied then a legend is added to the plot. If \code{legend} is a
#' character vector then it is used as the argument \code{legend}
#' to \code{\link[graphics]{legend}}. Otherwise, i.e. if
#' \code{legend = TRUE} then the argument \code{type} is used.
#' @param legend_pos The position of the legend (if required) specified using
#' the argument \code{x} in \code{\link[graphics]{legend}}.
#' @param ... Additional arguments passed to \code{\link[graphics]{matplot}}
#' or \code{\link[graphics]{legend}}. The arguments \code{col}, \code{lty}
#' and \code{lwd} will be used (in a consistent way) by both
#' \code{\link[graphics]{matplot}} and \code{\link[graphics]{legend}}.
#'
#' If the argument \code{xlim} to \code{\link[graphics]{matplot}} is not
#' supplied then the MLE minus (for \code{lower}) or plus (for \code{upper})
#' standard errors is used. If \code{type} does not include 4 then adjusted
#' standard errors are used. Otherwise, the larger of the adjusted and
#' unadjusted standard errors are used.
#' @return Nothing is returned.
#' @examples
#' # ------------------------- Binomial model, rats data ----------------------
#'
#' # Contributions to the independence loglikelihood
#' binom_loglik <- function(prob, data) {
#' if (prob < 0 || prob > 1) {
#' return(-Inf)
#' }
#' return(dbinom(data[, "y"], data[, "n"], prob, log = TRUE))
#' }
#' rat_res <- adjust_loglik(loglik = binom_loglik, data = rats, par_names = "p")
#'
#' # Vertically adjusted loglikelihood only
#' plot(rat_res)
#' # Three adjusted loglikelihoods and the independence loglikelihood
#' plot(rat_res, type = 1:4)
#' # Plot over (0,1) and reposition the legend
#' plot(rat_res, type = 1:4, xlim = c(0, 1), legend_pos = "bottom")
#' @seealso \code{\link{adjust_loglik}} to adjust a user-supplied
#' loglikelihood function.
#' @seealso \code{\link{summary.chandwich}} for maximum likelihood estimates
#' and unadjusted and adjusted standard errors.
#' @seealso \code{\link{conf_intervals}} and \code{\link{plot.confint}} to
#' plot confidence intervals for individual parameters.
#' @seealso \code{\link{conf_region}} and \code{\link{plot.confreg}} to
#' plot a confidence region for a pair of parameters.
#' @export
plot.chandwich <- function(x, y, type = 1, legend = length(type) > 1,
legend_pos = "topleft", ...) {
if (!inherits(x, "chandwich")) {
stop("use only with \"chandwich\" objects")
}
n_pars <- attr(x, "p_current")
if (n_pars != 1) {
stop("x must have one free parameter, i.e. attr(x, ''p_current'') = 1")
}
# User-supplied arguments
user_args <- list(...)
# Always plot lines only
user_args$type = "l"
l_cond <- names(user_args) %in% methods::formalArgs(graphics::legend)
lines_cond <- names(user_args) %in% c("col", "lty", "lwd")
legend_args <- user_args[l_cond]
user_args <- user_args[!l_cond | lines_cond]
# If xlab or ylab are not supplied then use names(x$which_pars), if present
if (is.null(user_args$xlab)) {
if (!is.null(names(attr(x, "free_pars")))) {
xlabel <- names(attr(x, "free_pars"))
} else {
xlabel <- ""
}
user_args$xlab <- parse(text = xlabel)
}
if (is.null(user_args$ylab)) {
user_args$ylab <- "loglikelihood"
}
if (is.null(user_args$xlim)) {
if (4 %in% type) {
lower <- attr(x, "MLE") - 3 * max(attr(x, "adjSE"), attr(x, "SE"))
upper <- attr(x, "MLE") + 3 * max(attr(x, "adjSE"), attr(x, "SE"))
} else {
lower <- attr(x, "MLE") - 3 * attr(x, "adjSE")
upper <- attr(x, "MLE") + 3 * attr(x, "adjSE")
}
user_args$xlim <- c(lower, upper)
}
if (is.null(user_args$col)) {
user_args$col <- rep(1, 4)
}
legend_args$col <- user_args$col
if (is.null(user_args$lty)) {
user_args$lty <- 1:4
}
legend_args$lty <- user_args$lty
if (is.null(user_args$lwd)) {
user_args$lwd <- rep(1, 4)
}
legend_args$lwd <- user_args$lwd
# Create values for the plot
x_vals <- seq(user_args$xlim[1], user_args$xlim[2], len = 100)
y_vals <- NULL
if (any(type == 1)) {
y_vals <- cbind(y_vals, x(x_vals, type = "vertical"))
}
if (any(type == 2)) {
y_vals <- cbind(y_vals, x(x_vals, type = "cholesky"))
}
if (any(type == 3)) {
y_vals <- cbind(y_vals, x(x_vals, type = "spectral"))
}
if (any(type == 4)) {
y_vals <- cbind(y_vals, x(x_vals, type = "none"))
}
for_matplot <- c(list(x = x_vals, y = y_vals), user_args)
do.call(graphics::matplot, for_matplot)
# Add a legend?
if (is.character(legend) || legend) {
types <- c("vertical", "cholesky", "spectral", "none")
legend_args$x <- legend_pos
if (is.logical(legend) && legend) {
legend_args$legend <- types[type]
} else {
legend_args$legend <- legend
}
if (is.null(legend_args$title)) {
legend_args$title <- "adjustment"
}
do.call(graphics::legend, legend_args)
}
return(invisible())
}
# ============================ summary.chandwich =============================
#' Summarizing adjusted loglikelihoods
#'
#' \code{summary} method for class "chandwich"
#'
#' @param object an object of class "chandwich", a result of a call to
#' \code{\link{adjust_loglik}}.
#' @param digits An integer. Used for number formatting with
#' \code{\link[base:Round]{signif}}.
#' @param ... Additional optional arguments. At present no optional
#' arguments are used.
#' @return Returns a numeric matrix with 3 columns and the number of rows
#' equal to the number of parameters in the current model, i.e.
#' \code{attr(object, "p_current")}.
#' The columns contain: the maximum likelihood estimates (MLE), unadjusted
#' standard errors (SE) and adjusted standard errors (adjSE).
#' @seealso \code{\link{adjust_loglik}} to adjust a user-supplied
#' loglikelihood function.
#' @seealso \code{\link{plot.chandwich}} for plots of one-dimensional adjusted
#' loglikelihoods.
#' @section Examples:
#' See the examples in \code{\link{adjust_loglik}}.
#' @export
summary.chandwich <- function(object,
digits = max(3, getOption("digits") - 3L),
...) {
if (!inherits(object, "chandwich")) {
stop("use only with \"chandwich\" objects")
}
mle <- signif(attr(object, "MLE"), digits = digits)
SE <- signif(attr(object, "SE"), digits = digits)
adjSE <- signif(attr(object, "adjSE"), digits = digits)
res <- cbind(MLE = mle, SE = SE, `adj. SE` = adjSE)
if (is.null(attr(object, "par_names"))) {
rownames(res) <- 1:length(mle)
}
class(res) <- "summary.chandwich"
return(res)
}
# ======================== print.summary.chandwich ============================
#' Print method for objects of class "summary.chandwich"
#'
#' \code{print} method for an object \code{x} of class "summary.chandwich".
#'
#' @param x An object of class "summary.chandwich", a result of a call to
#' \code{\link{summary.chandwich}}.
#' @param ... Additional arguments passed on to \code{print}.
#' @return Prints a numeric matrix with 3 columns and the number of rows
#' equal to the number of parameters in the current model, i.e.
#' \code{attr(object, "p_current")}.
#' The columns contain: the maximum likelihood estimates (MLE), unadjusted
#' standard errors (SE) and adjusted standard errors (adjSE).
#' @seealso \code{\link{adjust_loglik}} to adjust a user-supplied
#' loglikelihood.
#' @seealso \code{\link{summary.chandwich}} for a diagnostic plot.
#' @section Examples:
#' See the examples in \code{\link{adjust_loglik}}.
#' @export
print.summary.chandwich <- function(x, ...) {
if (!inherits(x, "summary.chandwich")) {
stop("use only with \"summary.chandwich\" objects")
}
class(x) <- "matrix"
print(x, ...)
invisible(x)
}
# ============================== print.chandwich ==============================
#' Print method for objects of class "chandwich"
#'
#' \code{print} method for class "chandwich".
#'
#' @param x an object of class "chandwich", a result of a call to
#' \code{\link{adjust_loglik}}.
#' @param ... Additional optional arguments. At present no optional
#' arguments are used.
#' @details Just prints the original call to \code{\link{adjust_loglik}}
#' and a character vector giving the names of the attributes
#' (produced using \code{ls(attributes(x))}) to the function returned
#' from \code{\link{adjust_loglik}}.
#' To view an individual attribute called \code{att_name} use
#' \code{attr(x, "att_name")} or \code{attributes(x)$att_name}.
#' @return The argument \code{x}, invisibly, as for all
#' \code{\link[base]{print}} methods.
#' @seealso \code{\link{summary.chandwich}}: \code{summary} method for
#' class "chandwich".
#' @seealso \code{\link{adjust_loglik}} to adjust a user-supplied
#' loglikelihood.
#' @export
print.chandwich <- function(x, ...) {
if (!inherits(x, "chandwich")) {
stop("use only with \"chandwich\" objects")
}
cat("\n", "Call:", paste(deparse(attr(x, "call"))), "\n", "\n")
cat("Attributes, access using attr(., \"name\") or attributes(.)$name", "\n")
print(ls(attributes(x)))
return(invisible(x))
}
# ============================== plot.confreg =================================
#' Plot diagnostics for a confreg object
#'
#' \code{plot} method for class "confreg".
#' Plots confidence regions for pairs of parameters using the profile
#' loglikelihood values calculated by \code{\link{conf_region}}.
#' Up to 4 different types of loglikelihood (see the argument \code{type}
#' to the function returned by \code{\link{adjust_loglik}})
#' may be superimposed on the same plot.
#'
#' @param x,y,y2,y3 objects of class "confreg", results of calls to
#' \code{\link{conf_region}} for a common model and a common value of
#' \code{which_pars}. Contours are plotted for each object.
#' @param conf A numeric vector of confidence levels, i.e. numbers in
#' (0, 100). A confidence region contour is plotted for each value in
#' \code{conf}.
#' @param legend A logical scalar or a character vector. If this is
#' supplied then a legend is added to the plot. If \code{legend} is a
#' character vector then it is used as the argument \code{legend}
#' to \code{\link[graphics]{legend}}. Otherwise, i.e. if
#' \code{legend = TRUE} then the component \code{type} of the input
#' object(s) \code{x, y, y2, y3} are used.
#' @param legend_pos The position of the legend (if required) specified using
#' the argument \code{x} in \code{\link[graphics]{legend}}.
#' @param ... Additional arguments passed to \code{\link[graphics]{contour}}
#' or \code{\link[graphics]{legend}}. The arguments \code{col}, \code{lty}
#' and \code{lwd} will be used (in a consistent way) by both
#' \code{\link[graphics]{contour}} and \code{\link[graphics]{legend}}.
#' @return Nothing is returned.
#' @seealso \code{\link{adjust_loglik}} to adjust a user-supplied
#' loglikelihood function.
#' @seealso \code{\link{conf_region}} for a confidence region for
#' a pair of parameters.
#' @seealso \code{\link{conf_intervals}} and \code{\link{plot.confint}} to
#' plot confidence intervals for individual parameters.
#' @section Examples:
#' See the examples in \code{\link{conf_region}}.
#' @export
plot.confreg <- function(x, y = NULL, y2 = NULL, y3 = NULL, conf = 95,
legend = any(c(!is.null(y), !is.null(y2),
!is.null(y3))),
legend_pos = "topleft", ...) {
if (!inherits(x, "confreg")) {
stop("x must be a \"confreg\" object")
}
check_name <- x$name
# Check that all supplied objects have profiled the same parameters
if (!is.null(y)) {
if (!inherits(y, "confreg")) {
stop("y must be a \"confreg\" object")
}
if (!identical(x$which_pars, y$which_pars)) {
stop("y$which_pars is not identical to x$which_pars")
}
if (!identical(check_name, y$name)) {
stop("y is not derived from the same model as x")
}
}
if (!is.null(y2)) {
if (!inherits(y2, "confreg")) {
stop("y2 must be a \"confreg\" object")
}
if (!identical(x$which_pars, y2$which_pars)) {
stop("y2$which_pars is not identical to x$which_pars")
}
if (!identical(check_name, y2$name)) {
stop("y2 is not derived from the same model as x")
}
}
if (!is.null(y3)) {
if (!inherits(y3, "confreg")) {
stop("y3 must be a \"confreg\" object")
}
if (!identical(x$which_pars, y3$which_pars)) {
stop("y3$which_pars is not identical to x$which_pars")
}
if (!identical(check_name, y3$name)) {
stop("y3 is not derived from the same model as x")
}
}
# User-supplied arguments for contour
user_args <- list(...)
l_cond <- names(user_args) %in% methods::formalArgs(graphics::legend)
lines_cond <- names(user_args) %in% c("col", "lty", "lwd")
legend_args <- user_args[l_cond]
user_args <- user_args[!l_cond | lines_cond]
# If xlab or ylab are not supplied then use names(x$which_pars), if present
if (is.null(user_args$xlab)) {
if (is.null(names(x$which_pars))) {
user_args$xlab <- paste("parameter", x$which_pars[1])
} else {
user_args$xlab <- parse(text = names(x$which_pars)[1])
}
}
if (is.null(user_args$ylab)) {
if (is.null(names(x$which_pars))) {
user_args$ylab <- paste("parameter", x$which_pars[2])
} else {
user_args$ylab <- parse(text = names(x$which_pars)[2])
}
}
# If labels is not supplied then set it to confidence level
if (is.null(user_args$labels)) {
user_args$labels <- conf
}
# If drawlabels is not supplied then make it FALSE unless conf has length > 1
if (is.null(user_args$drawlabels)) {
user_args$drawlabels <- length(conf) > 1
}
if (is.null(user_args$xlim)) {
x_range <- range(x$grid1, y$grid1, y2$grid1, y3$grid1, finite = TRUE)
user_args$xlim <- x_range
}
if (is.null(user_args$ylim)) {
y_range <- range(x$grid2, y$grid2, y2$grid2, y3$grid2, finite = TRUE)
user_args$ylim <- y_range
}
if (is.null(user_args$col)) {
my_col <- rep(1, 4)
} else {
my_col <- rep_len(user_args$col, 4)
}
legend_args$col <- my_col
if (is.null(user_args$lty)) {
my_lty <- 1:4
} else {
my_lty <- rep_len(user_args$lty, 4)
}
legend_args$lty <- my_lty
if (is.null(user_args$lwd)) {
my_lwd <- rep(1, 4)
} else {
my_lwd <- rep_len(user_args$lwd, 4)
}
legend_args$lwd <- my_lwd
# Create plot using x
max_loglik <- x$max_loglik
cutoff <- max_loglik - stats::qchisq(conf / 100, 2) / 2
user_args$col <- my_col[1]
user_args$lty <- my_lty[1]
user_args$lwd <- my_lwd[1]
for_contour <- c(list(x = x$grid1, y = x$grid2, z = x$prof_loglik,
levels = cutoff), user_args)
do.call(graphics::contour, for_contour)
types <- x$type
# Add to plot using y
if (!is.null(y)) {
max_loglik <- y$max_loglik
cutoff <- max_loglik - stats::qchisq(conf / 100, 2) / 2
user_args$col <- my_col[2]
user_args$lty <- my_lty[2]
user_args$lwd <- my_lwd[2]
for_contour <- c(list(x = y$grid1, y = y$grid2, z = y$prof_loglik,
levels = cutoff, add = TRUE), user_args)
do.call(graphics::contour, for_contour)
types <- c(types, y$type)
}
# Add to plot using y2
if (!is.null(y2)) {
max_loglik <- y2$max_loglik
cutoff <- max_loglik - stats::qchisq(conf / 100, 2) / 2
user_args$col <- my_col[3]
user_args$lty <- my_lty[3]
user_args$lwd <- my_lwd[3]
for_contour <- c(list(x = y2$grid1, y = y2$grid2, z = y2$prof_loglik,
levels = cutoff, add = TRUE), user_args)
do.call(graphics::contour, for_contour)
types <- c(types, y2$type)
}
# Add to plot using y3
if (!is.null(y3)) {
max_loglik <- y3$max_loglik
cutoff <- max_loglik - stats::qchisq(conf / 100, 2) / 2
user_args$col <- my_col[4]
user_args$lty <- my_lty[4]
user_args$lwd <- my_lwd[4]
for_contour <- c(list(x = y3$grid1, y = y3$grid2, z = y3$prof_loglik,
levels = cutoff, add = TRUE), user_args)
do.call(graphics::contour, for_contour)
types <- c(types, y3$type)
}
# Add a legend?
if (is.character(legend) || legend) {
legend_args$x <- legend_pos
if (is.logical(legend) && legend) {
legend_args$legend <- types
} else {
legend_args$legend <- legend
}
if (is.null(legend_args$title)) {
legend_args$title <- "adjustment"
}
do.call(graphics::legend, legend_args)
}
return(invisible())
}
# ============================== plot.confint =================================
#' Plot diagnostics for a confint object
#'
#' \code{plot} method for class "confint".
#' Plots the (profile) loglikelihood for a parameter using the values
#' calculated by \code{\link{conf_intervals}}.
#' Up to 4 different types of loglikelihood (see the argument \code{type}
#' to the function returned by \code{\link{adjust_loglik}})
#' may be superimposed on the same plot.
#' By default (\code{add_lines = TRUE}) the confidence limits calculated
#' in \code{\link{conf_intervals}} are indicated on the plot .
#'
#' @param x,y,y2,y3 objects of class \code{"confint"}, results of calls to
#' \code{\link{conf_intervals}} for a common model. A (profile)
#' loglikelihood will be plotted for each object.
#' @param which_par A scalar specifying the parameter for which the plot
#' is produced. Can be either a numeric scalar, specifying index of the
#' component of the \strong{full} parameter vector, or a character scalar
#' parameter name. The former must be in \code{x$which_pars}, the latter
#' must be in \code{names(x$which_pars)}.
#' @param add_lines A logical scalar. Whether or not to add horizontal lines
#' to the plot to identify the confidence limits. If there is only one
#' input \code{"confint"} object then the values of the confidence limits
#' will be added to the horizontal axis.
#' @param conf A numeric vector of values in (0, 100). If
#' \code{add_lines = TRUE} then a horizontal line is added for each
#' value in \code{conf}. If \code{conf} is not supplied then the
#' value stored in \code{x$conf} is used.
#' @param legend A logical scalar or a character vector. If this is
#' supplied then a legend is added to the plot. If \code{legend} is a
#' character vector then it is used as the argument \code{legend}
#' to \code{\link[graphics]{legend}}. Otherwise, i.e. if
#' \code{legend = TRUE} then the component \code{type} of the input
#' object(s) \code{x, y, y2, y3} are used.
#' @param legend_pos The position of the legend (if required) specified using
#' the argument \code{x} in \code{\link[graphics]{legend}}.
#' @param ... Additional arguments passed to \code{\link[graphics]{matplot}}
#' or \code{\link[graphics]{legend}}. The arguments \code{col}, \code{lty}
#' and \code{lwd} will be used (in a consistent way) by both
#' \code{\link[graphics]{matplot}} and \code{\link[graphics]{legend}}.
#' @return Nothing is returned.
#' @seealso \code{\link{adjust_loglik}} to adjust a user-supplied
#' loglikelihood function.
#' @seealso \code{\link{conf_intervals}} for confidence intervals for
#' individual parameters.
#' @seealso \code{\link{conf_region}} and \code{\link{plot.confreg}} to
#' plot a confidence region for a pair of parameters.
#' @section Examples:
#' See the examples in \code{\link{conf_intervals}}.
#' @export
plot.confint <- function(x, y = NULL, y2 = NULL, y3 = NULL,
which_par = x$which_pars[1], conf = x$conf,
add_lines = TRUE,
legend = any(c(!is.null(y), !is.null(y2),
!is.null(y3))),
legend_pos = "topleft", ...) {
if (!inherits(x, "confint")) {
stop("x must be a \"confint\" object")
}
if (length(which_par) != 1) {
stop("which_par must have length one")
}
# Where is which_par positioned in x$which_pars
if (is.numeric(which_par)) {
which_index <- match(which_par, x$which_pars)
if (!is.null(names(x$which_pars))) {
par_names <- names(x$which_pars)
xlabel <- par_names[which_index]
} else {
xlabel <- ""
}
} else if (is.character(which_par)) {
if (is.null(names(x$which_pars))) {
stop("which_par can be character only if names(x$which_pars) isn't NULL")
}
par_names <- names(x$which_pars)
which_index <- match(which_par, par_names)
which_par <- x$which_pars[which_index]
xlabel <- par_names[which_index]
} else {
stop("which_par must be numeric or character")
}
# Function to extract the desired values from the input objects
extract_values <- function(object) {
if (which_par %in% object$which_pars) {
which_column <- match(which_par, object$which_pars)
x_vals <- object$parameter_vals[, which_column]
y_vals <- object$prof_loglik_vals[, which_column]
} else {
stop("Numeric which_par must be in object$which_pars")
}
return(list(x_vals = x_vals, y_vals = y_vals))
}
# Pick the correct columns in x$parameter_vals and x$prof_loglik_vals
temp <- extract_values(x)
x_vals <- temp$x_vals
y_vals <- temp$y_vals
types <- x$type
check_name <- attr(x, "name")
if (!is.null(y)) {
if (!inherits(y, "confint")) {
stop("y must be a \"confint\" object")
}
temp <- extract_values(y)
x_vals <- cbind(x_vals, temp$x_vals)
y_vals <- cbind(y_vals, temp$y_vals)
types <- c(types, y$type)
}
if (!is.null(y2)) {
if (!inherits(y2, "confint")) {
stop("y2 must be a \"confint\" object")
}
temp <- extract_values(y2)
x_vals <- cbind(x_vals, temp$x_vals)
y_vals <- cbind(y_vals, temp$y_vals)
types <- c(types, y2$type)
}
if (!is.null(y3)) {
if (!inherits(y3, "confint")) {
stop("y3 must be a \"confint\" object")
}
temp <- extract_values(y3)
x_vals <- cbind(x_vals, temp$x_vals)
y_vals <- cbind(y_vals, temp$y_vals)
types <- c(types, y3$type)
}
# User-supplied arguments
user_args <- list(...)
# Always plot lines only
user_args$type = "l"
l_cond <- names(user_args) %in% methods::formalArgs(graphics::legend)
lines_cond <- names(user_args) %in% c("col", "lty", "lwd")
legend_args <- user_args[l_cond]
user_args <- user_args[!l_cond | lines_cond]
# If xlab or ylab are not supplied then use names(x$which_pars), if present
if (is.null(user_args$xlab)) {
user_args$xlab <- parse(text = xlabel)
}
if (is.null(user_args$ylab)) {
if (x$p_current == 1) {
user_args$ylab <- "loglikelihood"
} else {
user_args$ylab <- "profile loglikelihood"
}
}
if (is.null(user_args$xlim)) {
x_range <- range(x_vals, finite = TRUE)
user_args$xlim <- x_range
}
if (is.null(user_args$ylim)) {
y_range <- range(y_vals, finite = TRUE)
user_args$ylim <- y_range
}
if (is.null(user_args$col)) {
user_args$col <- rep(1, 4)
}
legend_args$col <- user_args$col
if (is.null(user_args$lty)) {
user_args$lty <- 1:4
}
legend_args$lty <- user_args$lty
if (is.null(user_args$lwd)) {
user_args$lwd <- rep(1, 4)
}
legend_args$lwd <- user_args$lwd
for_matplot <- c(list(x = x_vals, y = y_vals), user_args)
do.call(graphics::matplot, for_matplot)
cutoff <- x$max_loglik - stats::qchisq(conf / 100, 1) / 2
if (add_lines) {
graphics::abline(h = cutoff)
# If there is only one confidence interval then add the confidence limits
# on the horizontal axis
if (is.null(y) && is.null(y2) && is.null(y3)) {
which_CI <- x$prof_CI[which_index, ]
graphics::axis(1, at = which_CI, labels = round(which_CI, 3),
tick = FALSE, mgp = c(3, 0.15, 0))
}
}
# Add a legend?
if (is.character(legend) || legend) {
legend_args$x <- legend_pos
if (is.logical(legend) && legend) {
legend_args$legend <- types
} else {
legend_args$legend <- legend
}
if (is.null(legend_args$title)) {
legend_args$title <- "adjustment"
}
do.call(graphics::legend, legend_args)
}
return(invisible())
}
# =============================== print.confint ===============================
#' Print method for objects of class "confint"
#'
#' \code{print} method for class "confint".
#'
#' @param x an object of class "confint", a result of a call to
#' \code{\link{conf_intervals}}.
#' @param digits An integer. The argument \code{digits} to
#' \code{\link[base]{print.default}}.
#' @param ... Additional optional arguments. At present no optional
#' arguments are used.
#' @details Prints the name of the model, details of any fixed parameters,
#' the confidence level of the interval(s) and whether or not
#' the loglikelihood has been adjusted, and symmetric and (profile) likelihood
#' based intervals.
#' @return The argument \code{x}, invisibly, as for all
#' \code{\link[base]{print}} methods.
#' @seealso \code{\link{adjust_loglik}} to adjust a user-supplied
#' loglikelihood function.
#' @seealso \code{\link{conf_intervals}} for confidence intervals for
#' individual parameters.
#' @section Examples:
#' See the examples in \code{\link{conf_intervals}}.
#' @export
print.confint <- function(x, digits = max(3L, getOption("digits") - 3L), ...) {
if (!inherits(x, "confint")) {
stop("use only with \"confint\" objects")
}
cat("Model:", x$name, "\n")
if (!is.null(x$fixed_pars)) {
if (length(x$fixed_pars) == 1) {
par_text <- "Fixed parameter:"
my_first <- 1
} else {
par_text <- "Fixed parameters:"
my_first <- 2
}
vals_text <- substring(deparse(as.numeric(x$fixed_at)), first = my_first)
if (is.null(names(x$fixed_pars))) {
names_text <- substring(deparse(x$fixed_pars), first = my_first)
} else {
names_text <- substring(deparse(names(x$fixed_pars)), first = my_first)
}
cat(par_text, names_text, "=", vals_text, "\n")
}
cat("\n")
conf_level <- paste(x$conf, "%", sep = "")
if (x$p_current == 1) {
conf_name <- "confidence interval,"
} else {
conf_name <- "confidence intervals,"
}
if (x$type == "none") {
cat(conf_level, conf_name, "independence loglikelihood\n")
} else {
cat(conf_level, conf_name, "adjusted loglikelihod with type =",
paste("''", x$type, "''", sep = ""), "\n")
}
cat("\n")
cat("Symmetric:\n")
print.default(format(x$sym_CI, digits = digits), print.gap = 2L,
quote = FALSE)
cat("\n")
if (x$p_current == 1) {
cat("Likelihood-based:\n")
} else {
cat("Profile likelihood-based:\n")
}
print.default(format(x$prof_CI, digits = digits), print.gap = 2L,
quote = FALSE)
return(invisible(x))
}
# =============================== print.compmod ===============================
#' Print method for objects of class "compmod"
#'
#' \code{print} method for class "compmod".
#'
#' @param x an object of class "compmod", a result of a call to
#' \code{\link{compare_models}}.
#' @param digits An integer. The argument \code{digits} to
#' \code{\link[base:Round]{signif}}.
#' @param ... Additional optional arguments. At present no optional
#' arguments are used.
#' @details Prints the name of the model, the null (H0) and alternative
#' hypotheses (HA), the test statistic, degrees of freedom and the p-value.
#' If the test is based on the approximation detailed by equations (18)-(20)
#' of Chandler and Bate (2007), rather than equation (17), then this stated.
#' @return The argument \code{x}, invisibly, as for all
#' \code{\link[base]{print}} methods.
#' @seealso \code{\link{adjust_loglik}} to adjust a user-supplied
#' loglikelihood function.
#' @seealso \code{\link{compare_models}} to compare nested models using an
#' (adjusted) likelihood ratio test.
#' @section Examples:
#' See the examples in \code{\link{compare_models}}.
#' @export
print.compmod <- function(x, digits = max(3L, getOption("digits") - 3L), ...) {
if (!inherits(x, "compmod")) {
stop("use only with \"compmod\" objects")
}
cat("Model:", x$name, "\n")
if (length(x$smaller_fixed_pars) == 1) {
my_first <- 1
} else {
my_first <- 2
}
if (is.null(names(x$smaller_fixed_pars))) {
names_text <- substring(deparse(x$smaller_fixed_pars), first = my_first)
} else {
names_text <- substring(deparse(names(x$smaller_fixed_pars)),
first = my_first)
}
vals_text <- substring(deparse(as.numeric(x$smaller_fixed_at)),
first = my_first)
cat("H0:", names_text, "=", vals_text, "\n")
if (is.null(x$larger_fixed_pars)) {
cat("HA:", "unrestricted model", "\n")
} else {
if (length(x$larger_fixed_pars) == 1) {
my_first <- 1
} else {
my_first <- 2
}
if (is.null(names(x$larger_fixed_pars))) {
names_text <- substring(deparse(x$larger_fixed_pars), first = my_first)
} else {
names_text <- substring(deparse(names(x$larger_fixed_pars)),
first = my_first)
}
vals_text <- substring(deparse(as.numeric(x$larger_fixed_at)),
first = my_first)
cat("HA:", names_text, "=", vals_text, "\n")
}
cat("\n")
if (x$approx) {
cat("Using using approximation (18) of Chandler and Bate (2007):", "\n")
}
out <- character()
out <- c(out, paste("test statistic", "=", format(signif(x$alrts, digits))))
out <- c(out, paste("df", "=", format(signif(x$df, digits))))
out <- c(out, paste("p-value", "=", format(signif(x$p_value, digits))))
cat(strwrap(paste(out, collapse = ", ")), sep = "\\n")
return(invisible(x))
}