|
1 | 1 | #' Convert to tibble |
2 | 2 | #' |
3 | | -#' Converts an `epi_df` object into a tibble, dropping metadata and any |
4 | | -#' grouping. |
| 3 | +#' Converts an `epi_df` object into a tibble, dropping metadata, any |
| 4 | +#' grouping, and any unrelated classes and attributes. |
5 | 5 | #' |
6 | 6 | #' Advanced: if you are working with a third-party package that uses |
7 | 7 | #' `as_tibble()` on `epi_df`s but you actually want them to remain `epi_df`s, |
8 | 8 | #' use `attr(your_epi_df, "decay_to_tibble") <- FALSE` beforehand. |
9 | 9 | #' |
10 | 10 | #' @param x an `epi_df` |
11 | | -#' @inheritParams tibble::as_tibble |
12 | | -#' @importFrom tibble as_tibble |
| 11 | +#' @param ... if present, forwarded to [`tibble::as_tibble`] |
| 12 | +#' @importFrom tibble as_tibble new_tibble |
| 13 | +#' @importFrom rlang dots_n |
| 14 | +#' @importFrom vctrs vec_data vec_size |
13 | 15 | #' @export |
14 | 16 | as_tibble.epi_df <- function(x, ...) { |
15 | 17 | # Note that some versions of `tsibble` overwrite `as_tibble.grouped_df`, which |
16 | | - # also impacts grouped `epi_df`s don't rely on `NextMethod()`. Destructure |
17 | | - # first instead. |
18 | | - destructured <- tibble::as_tibble(vctrs::vec_data(x), ...) |
| 18 | + # also impacts grouped `epi_df`s, so don't rely on `NextMethod()`. Destructure |
| 19 | + # and redispatch instead. |
| 20 | + destructured <- vec_data(x) # -> data.frame, dropping extra attrs |
| 21 | + tbl <- if (dots_n(...) == 0 && |
| 22 | + is.null(pkgconfig::get_config("tibble::rownames"))) { |
| 23 | + # perf: new_tibble instead of as_tibble.data.frame which performs |
| 24 | + # extra checks whose defaults should be redundant here: |
| 25 | + new_tibble(destructured) |
| 26 | + # (^ We don't need to provide nrow= as we have >0 columns.) |
| 27 | + } else { |
| 28 | + as_tibble(destructured, ...) |
| 29 | + } |
19 | 30 | if (attr(x, "decay_to_tibble") %||% TRUE) { |
20 | | - return(destructured) |
| 31 | + return(tbl) |
21 | 32 | } else { |
22 | 33 | # We specially requested via attr not to decay epi_df-ness but to drop any |
23 | | - # grouping. |
24 | | - reclass(destructured, attr(x, "metadata")) |
| 34 | + # grouping. (Miscellaneous attrs are also dropped.) |
| 35 | + reclass(tbl, attr(x, "metadata")) |
25 | 36 | } |
26 | 37 | } |
27 | 38 |
|
|
0 commit comments