/R/ks-tidiers.R

https://github.com/tidymodels/broom · R · 70 lines · 24 code · 2 blank · 44 comment · 0 complexity · 6e8231eb2990b2dee4dc6e76a4e1a226 MD5 · raw file

  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. #' @examples
  14. #'
  15. #' library(ks)
  16. #'
  17. #' dat <- replicate(2, rnorm(100))
  18. #' k <- kde(dat)
  19. #'
  20. #' td <- tidy(k)
  21. #' td
  22. #'
  23. #' library(ggplot2)
  24. #' library(dplyr)
  25. #' library(tidyr)
  26. #'
  27. #' td %>%
  28. #' pivot_wider(c(obs, estimate),
  29. #' names_from = variable,
  30. #' values_from = value
  31. #' ) %>%
  32. #' ggplot(aes(x1, x2, fill = estimate)) +
  33. #' geom_tile() +
  34. #' theme_void()
  35. #'
  36. #' # also works with 3 dimensions
  37. #' dat3 <- replicate(3, rnorm(100))
  38. #' k3 <- kde(dat3)
  39. #'
  40. #' td3 <- tidy(k3)
  41. #' td3
  42. #' @export
  43. #' @aliases kde_tidiers ks_tidiers
  44. #' @seealso [tidy()], [ks::kde()]
  45. tidy.kde <- function(x, ...) {
  46. estimate <- x$estimate %>%
  47. as.data.frame.table(responseName = "value") %>%
  48. dplyr::mutate_if(is.factor, as.integer)
  49. dims <- seq_len(length(x$eval.points))
  50. purrr::map2(
  51. x$eval.points,
  52. estimate[dims],
  53. function(e, d) e[d]
  54. ) %>%
  55. purrr::set_names(paste0("x", dims)) %>%
  56. as_tibble() %>%
  57. mutate(
  58. estimate = estimate$value,
  59. obs = row_number()
  60. ) %>%
  61. pivot_longer(
  62. cols = c(dplyr::everything(), -estimate, -obs),
  63. names_to = "variable",
  64. values_to = "value"
  65. ) %>%
  66. arrange(variable, obs) %>%
  67. select(obs, variable, value, estimate)
  68. }