0

MRE:

library(tsibble)
#> Warning in system("timedatectl", intern = TRUE): running command 'timedatectl'
#> had status 1
library(tidyr)

my_tsibble <- structure(list(date = structure(c(18388, 18389, 18390, 18391, 
                                             18392, 18393), class = "Date"), new_cases = c(1444, 1401, 1327, 
                                                                                           1083, 802, NA)), row.names = c(NA, -6L), key = structure(list(
                                                                                             .rows = list(1:6)), row.names = c(NA, -1L), class = c("tbl_df", 
                                                                                                                                                   "tbl", "data.frame")), index = structure("date", ordered = TRUE), index2 = "date", interval = structure(list(
                                                                                                                                                     year = 0, quarter = 0, month = 0, week = 0, day = 1, hour = 0, 
                                                                                                                                                     minute = 0, second = 0, millisecond = 0, microsecond = 0, 
                                                                                                                                                     nanosecond = 0, unit = 0), class = "interval"), class = c("tbl_ts", 
                                                                                                                                                                                                               "tbl_df", "tbl", "data.frame"))
drop_na(my_tsibble)
#> # A tibble: 5 x 2
#>   date       new_cases
#>   <date>         <dbl>
#> 1 2020-05-06      1444
#> 2 2020-05-07      1401
#> 3 2020-05-08      1327
#> 4 2020-05-09      1083
#> 5 2020-05-10       802

换句话说,从 a 开始tsibble并使用drop_na删除最后一行,我得到了一个tibble. 这很烦人,因为为了应用预测方法,fable我需要my_tsibble成为tsibble. 如何在NA不丢失tsibble类型的情况下删除值?

4

1 回答 1

1

您的问题的答案是您可以使用; 只是结果对象在过程中被强制转换为 a 。原因是这是包中的通用函数。没有在任何地方指定用于处理不同的方法。因此只输出小标题或数据帧。另一种看待它的方式是,它从未听说过 a ,但它知道它继承自,并照此对待。drop_natsibbletibbledrop_natidyrtsibbledrop_nadrop_natsibbletibble

但是,您可以定义一个新的 S3 方法drop_na.tbl_ts来为您完成这项工作:

drop_na.tbl_ts <- function(ts) tsibble::as_tsibble(tidyr:::drop_na.data.frame(ts))

所以现在drop_na按预期工作:

drop_na(my_tsibble)
#> Using `date` as index variable.
#> # A tsibble: 5 x 2 [1D]
#>   date       new_cases
#>   <date>         <dbl>
#> 1 2020-05-06      1444
#> 2 2020-05-07      1401
#> 3 2020-05-08      1327
#> 4 2020-05-09      1083
#> 5 2020-05-10       802
于 2020-05-12T13:41:59.387 回答