Debian Codegraph @

R/zoo.R

raw
1 #' @templateVar class zoo
2 #' @template title_desc_tidy
3 #'
4 #' @param x A `zoo` object such as those created by [zoo::zoo()].
5 #' @template param_unused_dots
6 #'
7 #' @evalRd return_tidy("index", "series", "value")
8 #'
9 #' @examplesIf rlang::is_installed(c("zoo", "ggplot2"))
10 #'
11 #' # load libraries for models and data
12 #' library(zoo)
13 #' library(ggplot2)
14 #'
15 #' set.seed(1071)
16 #'
17 #' # generate data
18 #' Z.index <- as.Date(sample(12450:12500, 10))
19 #' Z.data <- matrix(rnorm(30), ncol = 3)
20 #' colnames(Z.data) <- c("Aa", "Bb", "Cc")
21 #' Z <- zoo(Z.data, Z.index)
22 #'
23 #' # summarize model fit with tidiers + visualization
24 #' tidy(Z)
25 #'
26 #' ggplot(tidy(Z), aes(index, value, color = series)) +
27 #' geom_line()
28 #'
29 #' ggplot(tidy(Z), aes(index, value)) +
30 #' geom_line() +
31 #' facet_wrap(~series, ncol = 1)
32 #'
33 #' Zrolled <- rollmean(Z, 5)
34 #' ggplot(tidy(Zrolled), aes(index, value, color = series)) +
35 #' geom_line()
36 #'
37 #' @aliases zoo_tidiers
38 #' @export
39 #' @seealso [tidy()], [zoo::zoo()]
40 #' @family time series tidiers
41 tidy.zoo <- function(x, ...) {
42 # check for univariate zoo series
43 if (length(dim(x)) > 0) {
44 ret <- data.frame(as.matrix(x), index = zoo::index(x))
45 ret <- tibble::as_tibble(ret)
46 if (!is.null(colnames(x))) {
47 colnames(ret)[1:ncol(x)] <- colnames(x)
48 }
49
50 out <- pivot_longer(
51 ret,
52 cols = c(dplyr::everything(), -index),
53 names_to = "series",
54 values_to = "value"
55 )
56 } else {
57 out <- tibble::tibble(
58 index = zoo::index(x),
59 value = zoo::coredata(x)
60 )
61 }
62 return(out)
63 }