| 1 |
#' @templateVar class ts |
| 2 |
#' @template title_desc_tidy |
| 3 |
#' |
| 4 |
#' @param x A univariate or multivariate `ts` times series object. |
| 5 |
#' @template param_unused_dots |
| 6 |
#' |
| 7 |
#' @evalRd return_tidy("index", "series", "value") |
| 8 |
#' |
| 9 |
#' @details `series` column is only present for multivariate `ts` objects. |
| 10 |
#' |
| 11 |
#' @examples |
| 12 |
#' |
| 13 |
#' set.seed(678) |
| 14 |
#' |
| 15 |
#' tidy(ts(1:10, frequency = 4, start = c(1959, 2))) |
| 16 |
#' |
| 17 |
#' z <- ts(matrix(rnorm(300), 100, 3), start = c(1961, 1), frequency = 12) |
| 18 |
#' colnames(z) <- c("Aa", "Bb", "Cc") |
| 19 |
#' |
| 20 |
#' tidy(z) |
| 21 |
#' @export |
| 22 |
#' @seealso [tidy()], [stats::ts()] |
| 23 |
#' @family time series tidiers |
| 24 |
#' |
| 25 |
tidy.ts <- function(x, ...) { |
| 26 |
# This generates the "index" column using the same approach as time(x), but |
| 27 |
# without converting to a ts object. |
| 28 |
xtsp <- stats::tsp(x) |
| 29 |
index <- seq(xtsp[1], xtsp[2], by = 1 / xtsp[3]) |
| 30 |
# Turn multi-column time series into tidy data frames. |
| 31 |
if (is.matrix(x)) { |
| 32 |
res <- as_tibble(as.data.frame(x)) |
| 33 |
res <- tibble::add_column(res, index = index, .before = 1) |
| 34 |
res |> |
| 35 |
pivot_longer( |
| 36 |
cols = c(dplyr::everything(), -index), |
| 37 |
names_to = "series", |
| 38 |
values_to = "value" |
| 39 |
) |
| 40 |
} else { |
| 41 |
tibble(index = index, value = as.vector(x)) |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
#' @templateVar class acf |
| 46 |
#' @template title_desc_tidy |
| 47 |
#' |
| 48 |
#' @param x An `acf` object created by [stats::acf()], [stats::pacf()] or |
| 49 |
#' [stats::ccf()]. |
| 50 |
#' @template param_unused_dots |
| 51 |
#' |
| 52 |
#' @evalRd return_tidy("lag", "acf") |
| 53 |
#' |
| 54 |
#' @examples |
| 55 |
#' |
| 56 |
#' tidy(acf(lh, plot = FALSE)) |
| 57 |
#' tidy(ccf(mdeaths, fdeaths, plot = FALSE)) |
| 58 |
#' tidy(pacf(lh, plot = FALSE)) |
| 59 |
#' @export |
| 60 |
#' @seealso [tidy()], [stats::acf()], [stats::pacf()], [stats::ccf()] |
| 61 |
#' @family time series tidiers |
| 62 |
tidy.acf <- function(x, ...) { |
| 63 |
tibble(lag = as.numeric(x$lag), acf = as.numeric(x$acf)) |
| 64 |
} |
| 65 |
|
| 66 |
|
| 67 |
#' @templateVar class spec |
| 68 |
#' @template title_desc_tidy |
| 69 |
#' |
| 70 |
#' @param x A `spec` object created by [stats::spectrum()]. |
| 71 |
#' @template param_unused_dots |
| 72 |
#' |
| 73 |
#' @evalRd return_tidy("freq", "spec") |
| 74 |
#' |
| 75 |
#' @examplesIf rlang::is_installed("ggplot2") |
| 76 |
#' |
| 77 |
#' spc <- spectrum(lh) |
| 78 |
#' tidy(spc) |
| 79 |
#' |
| 80 |
#' library(ggplot2) |
| 81 |
#' ggplot(tidy(spc), aes(freq, spec)) + |
| 82 |
#' geom_line() |
| 83 |
#' @export |
| 84 |
#' @seealso [tidy()], [stats::spectrum()] |
| 85 |
#' @family time series tidiers |
| 86 |
tidy.spec <- function(x, ...) { |
| 87 |
as_tibble(x[c("freq", "spec")]) |
| 88 |
} |