Debian Codegraph @

R/ks.R

raw
1 #' @templateVar class kde
2 #' @template title_desc_tidy
3 #'
4 #' @param x A `kde` object returned from [ks::kde()].
5 #' @template param_unused_dots
6 #'
7 #' @evalRd return_tidy("obs", "variable", "value", "estimate")
8 #'
9 #' @details Returns a data frame in long format with four columns. Use
10 #' \code{tidyr::pivot_wider(..., names_from = variable, values_from = value)}
11 #' on the output to return to a wide format.
12 #'
13 #' @examplesIf rlang::is_installed(c("ks", "ggplot2"))
14 #'
15 #' # load libraries for models and data
16 #' library(ks)
17 #'
18 #' # generate data
19 #' dat <- replicate(2, rnorm(100))
20 #' k <- kde(dat)
21 #'
22 #' # summarize model fit with tidiers + visualization
23 #' td <- tidy(k)
24 #' td
25 #'
26 #' library(ggplot2)
27 #' library(dplyr)
28 #' library(tidyr)
29 #'
30 #' td |>
31 #' pivot_wider(c(obs, estimate),
32 #' names_from = variable,
33 #' values_from = value
34 #' ) |>
35 #' ggplot(aes(x1, x2, fill = estimate)) +
36 #' geom_tile() +
37 #' theme_void()
38 #'
39 #' # also works with 3 dimensions
40 #' dat3 <- replicate(3, rnorm(100))
41 #' k3 <- kde(dat3)
42 #'
43 #' td3 <- tidy(k3)
44 #' td3
45 #'
46 #' @export
47 #' @aliases kde_tidiers ks_tidiers
48 #' @seealso [tidy()], [ks::kde()]
49 tidy.kde <- function(x, ...) {
50 estimate <- x$estimate |>
51 as.data.frame.table(responseName = "value") |>
52 dplyr::mutate_if(is.factor, as.integer)
53
54 dims <- seq_len(length(x$eval.points))
55
56 purrr::map2(
57 x$eval.points,
58 estimate[dims],
59 function(e, d) e[d]
60 ) |>
61 purrr::set_names(paste0("x", dims)) |>
62 as_tibble() |>
63 mutate(
64 estimate = estimate$value,
65 obs = row_number()
66 ) |>
67 pivot_longer(
68 cols = c(dplyr::everything(), -estimate, -obs),
69 names_to = "variable",
70 values_to = "value"
71 ) |>
72 arrange(variable, obs) |>
73 select(obs, variable, value, estimate)
74 }