tidyverts / fabletools

General fable features useful for extension packages
http://fabletools.tidyverts.org/
89 stars 31 forks source link

Improve handling of renaming fable columns #348

Open mitchelloharawild opened 2 years ago

mitchelloharawild commented 2 years ago

Currently it drops the fable class, even if the renamed columns aren't special in anyway (key, index, distribution). It should be possible to rename all columns without issue, maintaining the fable class.

reprex provided by Eric Berger:

library(fpp3)
#> ── Attaching packages ──────────────────────────────────────────── fpp3 0.4.0 ──
#> ✓ tibble      3.1.6          ✓ tsibble     1.1.1     
#> ✓ dplyr       1.0.7          ✓ tsibbledata 0.4.0.9000
#> ✓ tidyr       1.1.4          ✓ feasts      0.2.2.9000
#> ✓ lubridate   1.8.0          ✓ fable       0.3.1.9000
#> ✓ ggplot2     3.3.5.9000
#> ── Conflicts ───────────────────────────────────────────────── fpp3_conflicts ──
#> x lubridate::date()    masks base::date()
#> x dplyr::filter()      masks stats::filter()
#> x tsibble::intersect() masks base::intersect()
#> x tsibble::interval()  masks lubridate::interval()
#> x dplyr::lag()         masks stats::lag()
#> x tsibble::setdiff()   masks base::setdiff()
#> x tsibble::union()     masks base::union()
N <- 20
a <- tsibble(date=2000+(1:N),x=runif(N),index=date)
a.lm <- a %>% model(tslm=TSLM(x ~ trend()))
a.fc <- a.lm %>% forecast(h=1)
hilo(a.fc,level=95)  ## outputs a tsibble
#> # A tsibble: 1 x 5 [1Y]
#> # Key:       .model [1]
#>   .model  date             x .mean                    `95%`
#>   <chr>  <dbl>        <dist> <dbl>                   <hilo>
#> 1 tslm    2021 N(0.45, 0.14) 0.453 [-0.2847969, 1.190116]95
### 
print(a.fc) ## a fable
#> # A fable: 1 x 4 [1Y]
#> # Key:     .model [1]
#>   .model  date             x .mean
#>   <chr>  <dbl>        <dist> <dbl>
#> 1 tslm    2021 N(0.45, 0.14) 0.453
class(a.fc) ## "fbl_ts" etc
#> [1] "fbl_ts"     "tbl_ts"     "tbl_df"     "tbl"        "data.frame"
colnames(a.fc)  ## ".model" "date" "x" ".mean"
#> [1] ".model" "date"   "x"      ".mean"
a.fc %>% rename(forecast = .mean)
#> # A tsibble: 1 x 4 [1Y]
#> # Key:       .model [1]
#>   .model  date             x forecast
#>   <chr>  <dbl>        <dist>    <dbl>
#> 1 tslm    2021 N(0.45, 0.14)    0.453
colnames(a.fc)[4] <- "forecast"
###
hilo(a.fc,level=95) ### Error
#> Error in `hilo()`:
#> ! Objects of type `tbl_ts` are not supported by `hilo()`, you can create a custom `hilo` with `new_hilo()`
#> • Objects of type `tbl_df` are not supported by `hilo()`, you can create a custom `hilo` with `new_hilo()`
#> • Objects of type `tbl` are not supported by `hilo()`, you can create a custom `hilo` with `new_hilo()`
#> • Objects of type `data.frame` are not supported by `hilo()`, you can create a custom `hilo` with `new_hilo()`
###
class(a.fc)
#> [1] "tbl_ts"     "tbl_df"     "tbl"        "data.frame"

Created on 2022-02-25 by the reprex package (v2.0.0)