From c0cfb855adf844dd2b6ae8b1edbb6189aac658b4 Mon Sep 17 00:00:00 2001 From: Mitchell O'Hara-Wild Date: Wed, 26 Jun 2024 10:29:40 +0200 Subject: [PATCH] Fix `difference()` giving extra NA values for short vectors (#311) Resolves #310 --- NEWS.md | 2 ++ R/time-wise.R | 2 +- tests/testthat/test-timewise.R | 5 +++++ 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index c0d20c14..afca65cd 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,5 @@ +* Fix `difference()` giving extra NA values when the time series is shorter than the lag length. (#310, @mitchelloharawild) + # tsibble 1.1.4 * Fixed `vec_ptype2()` for `yearweek` and `yearquarter` for non-default week start. (#299) diff --git a/R/time-wise.R b/R/time-wise.R index 397b96cf..418ed9f8 100644 --- a/R/time-wise.R +++ b/R/time-wise.R @@ -43,5 +43,5 @@ difference <- function(x, lag = 1, differences = 1, default = NA, diff_impl <- function(x, lag = 1, differences = 1, default = NA) { diff_x <- diff(x, lag = lag, differences = differences) - vec_c(vec_rep(default, lag * differences), diff_x) + vec_c(vec_rep(default, pmin(vec_size(x), lag * differences)), diff_x) } diff --git a/tests/testthat/test-timewise.R b/tests/testthat/test-timewise.R index bfb05a21..698d5ca2 100644 --- a/tests/testthat/test-timewise.R +++ b/tests/testthat/test-timewise.R @@ -21,3 +21,8 @@ test_that("difference() with `order_by`", { # right <- mutate(scrambled, diff = difference(value, order_by = year)), msg) # expect_equal(sort(right$diff, na.last = FALSE), difference(tsbl$value)) }) + + +test_that("difference() with short time series (#310)", { + expect_length(difference(1, differences = 3), 1L) +})