Skip to content

unnest does not work with tsibble being the elements of a column #296

@FinYang

Description

@FinYang
library(tidyverse)
library(tsibble)
#> 
#> Attaching package: 'tsibble'
#> The following object is masked from 'package:lubridate':
#> 
#>     interval
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, union
test <- tibble(a=1, b=list(tsibble(i = 1:10, x = rnorm(10), index = i)))
test
#> # A tibble: 1 × 2
#>       a b                
#>   <dbl> <list>           
#> 1     1 <tbl_ts [10 × 2]>
unnest(test, b)
#> Error in `validate_index()`:
#> ! Column `i` (index) must not contain `NA`.
#> Backtrace:
#>      ▆
#>   1. ├─tidyr::unnest(test, b)
#>   2. └─tidyr:::unnest.data.frame(test, b)
#>   3.   └─tidyr::unchop(...)
#>   4.     └─tidyr:::df_unchop(...)
#>   5.       └─vctrs::list_unchop(col, ptype = col_ptype)
#>   6.         └─vctrs (local) `<fn>`()
#>   7.           ├─vctrs:::vec_restore_dispatch(x = x, to = to)
#>   8.           └─tsibble:::vec_restore.tbl_ts(x = x, to = to)
#>   9.             └─tsibble::build_tsibble(...)
#>  10.               └─tsibble:::validate_index(tbl, !!qindex)
#>  11.                 └─rlang::abort(...)
unnest_tsibble(test, b)
#> Error in `validate_index()`:
#> ! Column `i` (index) must not contain `NA`.
#> Backtrace:
#>      ▆
#>   1. └─tsibble::unnest_tsibble(test, b)
#>   2.   ├─tidyr::unnest(as_tibble(data), cols = !!cols)
#>   3.   └─tidyr:::unnest.data.frame(as_tibble(data), cols = !!cols)
#>   4.     └─tidyr::unchop(...)
#>   5.       └─tidyr:::df_unchop(...)
#>   6.         └─vctrs::list_unchop(col, ptype = col_ptype)
#>   7.           └─vctrs (local) `<fn>`()
#>   8.             ├─vctrs:::vec_restore_dispatch(x = x, to = to)
#>   9.             └─tsibble:::vec_restore.tbl_ts(x = x, to = to)
#>  10.               └─tsibble::build_tsibble(...)
#>  11.                 └─tsibble:::validate_index(tbl, !!qindex)
#>  12.                   └─rlang::abort(...)

# Expected outcome
test %>%
  mutate(b = lapply(b, as_tibble)) %>%
  unnest(b) %>%
  as_tsibble(index = i, key = a)
#> # A tsibble: 10 x 3 [1]
#> # Key:       a [1]
#>        a     i       x
#>    <dbl> <int>   <dbl>
#>  1     1     1  0.0625
#>  2     1     2 -0.173 
#>  3     1     3 -0.283 
#>  4     1     4  2.33  
#>  5     1     5  0.181 
#>  6     1     6  0.340 
#>  7     1     7 -0.0122
#>  8     1     8 -0.988 
#>  9     1     9  0.827 
#> 10     1    10  0.679

Created on 2023-04-11 with reprex v2.0.2

If the output cannot be a tsibble since the method is on tibble, can it be a working tibble? Or at least with a more meaningful error message?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions