Debian Codegraph @

R/list-optim.R

raw
1 #' @templateVar class optim
2 #' @template title_desc_tidy_list
3 #'
4 #' @param x A list returned from [stats::optim()].
5 #' @template param_unused_dots
6 #'
7 #' @evalRd return_tidy(
8 #' "parameter",
9 #' "value",
10 #' "std.error",
11 #' .post = "\\code{std.error} is only provided as a column if the Hessian is calculated."
12 #' )
13 #'
14 #' @examples
15 #'
16 #' f <- function(x) (x[1] - 2)^2 + (x[2] - 3)^2 + (x[3] - 8)^2
17 #' o <- optim(c(1, 1, 1), f)
18 #'
19 #' @note
20 #' This function assumes that the provided objective function is a negative
21 #' log-likelihood function. Results will be invalid if an incorrect
22 #' function is supplied.
23 #'
24 #' tidy(o)
25 #' glance(o)
26 #' @aliases optim_tidiers tidy.optim
27 #' @family list tidiers
28 #' @seealso [tidy()], [stats::optim()]
29 tidy_optim <- function(x, ...) {
30 if (is.null(names(x$par))) {
31 names(x$par) <- paste0("parameter", seq_along(x$par))
32 }
33 ret <- tibble(parameter = names(x$par), value = unname(x$par))
34 if ("hessian" %in% names(x)) {
35 ret$std.error <- sqrt(diag(solve(x$hessian)))
36 }
37 ret
38 }
39
40 #' @templateVar class optim
41 #' @template title_desc_tidy_list
42 #'
43 #' @inherit tidy_optim params examples
44 #'
45 #' @evalRd return_glance(
46 #' "value",
47 #' "function.count",
48 #' "gradient.count",
49 #' "convergence"
50 #' )
51 #'
52 #' @aliases glance.optim
53 #' @family list tidiers
54 #' @seealso [glance()], [stats::optim()]
55 glance_optim <- function(x, ...) {
56 as_glance_tibble(
57 value = x$value,
58 function.count = unname(x$counts["function"]),
59 gradient.count = unname(x$counts["gradient"]),
60 convergence = x$convergence,
61 na_types = "riii"
62 )
63 }