1

鉴于:

test <- tsibble(
  date = lubridate::now() + 0:9,
  value = rnorm(10)
)  %>%
  mutate (vdiff =diff(value, differences = 2))

如何避免以下情况:

错误:mutate()列有问题vdiff。ℹ vdiff = diff(value, differences = 2, na.pad = TRUE)。ℹvdiff必须是 10 或 1 号,而不是 8 号

我尝试添加na.pad = TRUE但没有效果(无论如何,我宁愿用0not填充NA

4

1 回答 1

1

实现所需结果的一种方法是使用dplyr::lag. 然而,感谢@MitchellO'Hara-Wild 的评论,有一种更简单的方法可以通过简单地使用tsibble::difference

library(tsibble)
library(dplyr)

set.seed(42)

d <- tsibble(
  date = lubridate::now() + 0:9,
  value = rnorm(10)
)  
#> Using `date` as index variable.

d %>%
  mutate(vdiff = difference(value, differences = 2, default = 0))
#> # A tsibble: 10 x 3 [1s] <?>
#>    date                  value  vdiff
#>    <dttm>                <dbl>  <dbl>
#>  1 2021-06-20 14:33:28  1.37    0    
#>  2 2021-06-20 14:33:29 -0.565   0    
#>  3 2021-06-20 14:33:30  0.363   2.86 
#>  4 2021-06-20 14:33:31  0.633  -0.658
#>  5 2021-06-20 14:33:32  0.404  -0.498
#>  6 2021-06-20 14:33:33 -0.106  -0.282
#>  7 2021-06-20 14:33:34  1.51    2.13 
#>  8 2021-06-20 14:33:35 -0.0947 -3.22 
#>  9 2021-06-20 14:33:36  2.02    3.72 
#> 10 2021-06-20 14:33:37 -0.0627 -4.19
于 2021-06-20T11:35:45.070 回答