Skip to content

Commit

Permalink
questioning unnest_tsibble()
Browse files Browse the repository at this point in the history
  • Loading branch information
earowang committed Jun 7, 2019
1 parent ff06fdd commit 2070a3b
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 9 deletions.
15 changes: 7 additions & 8 deletions R/tidyr-verbs.R
Original file line number Diff line number Diff line change
Expand Up @@ -167,13 +167,12 @@ unnest_check_tsibble <- function(data, key, index) {
data
}

#' Unnest a data frame consisting of tsibbles to a tsibble
#'
#' @param data A data frame contains homogenous tsibbles in the list-columns.
#' @param cols Names of columns to unnest.
#' @inheritParams as_tsibble
#' @keywords internal
#' @examples
#' nested_stock %>%
#' unnest_tsibble(cols = data, key = stock)
#' @export
unnest_tsibble <- function(data, cols, key = NULL, validate = TRUE) {
if (missing(cols)) {
Expand All @@ -195,13 +194,13 @@ unnest_tsibble <- function(data, cols, key = NULL, validate = TRUE) {
new_lst <- unnested_names[map_lgl(unnested_data, is_list)]
old_lst <- data_names[map_lgl(data, is_list)]
lst_cols <- setdiff(old_lst, new_lst)
# checking if the nested columns has `tbl_ts` class (only for the first row)
first_nested <- data[lst_cols][1L, ]
eval_col <- purrr::imap(first_nested, dplyr::first)
tsbl_col <- map_lgl(eval_col, is_tsibble)
# checking if the nested columns has `tbl_ts` class
tsbl_col <- map_lgl(data[lst_cols], validate_list_of_tsibble)
if (sum(tsbl_col) == 0) {
abort("Unnested columns contain no tsibble object.")
abort("Unnested columns contain no tsibble columns.")
}
first_nested <- data[lst_cols][1L, ]
eval_col <- purrr::imap(first_nested, dplyr::first)

tsbl <- eval_col[tsbl_col][[1L]]
idx <- index(tsbl)
Expand Down
24 changes: 24 additions & 0 deletions man/unnest_tsibble.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion tests/testthat/test-tidyr.R
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ test_that("dplyr verbs for lst_ts", {
# )
expect_error(
unnest_tsibble(nest_t %>% mutate(data = 1), cols = data),
"contain no tsibble object."
"contain no tsibble columns."
)
expect_is(nest_t %>% select(data2 = data), "lst_ts")
expect_is(nest_t %>% group_by(State), "grouped_df")
Expand Down

0 comments on commit 2070a3b

Please sign in to comment.