Home > Software engineering >  Time series not working using by = argument in seq() function
Time series not working using by = argument in seq() function

Time:12-26

I am working through Time series analysis for the state/space model. In this book the author provides the following code

seq(from = as.Date("2001-01-01"),
    to = as.Date("2000-01-31"),
    by = "day")

Which generates the output

#  [1] "2001-01-01" "2000-12-20" "2000-12-08" "2000-11-27" "2000-11-15"
#  [6] "2000-11-04" "2000-10-23" "2000-10-11" "2000-09-30" "2000-09-18"
# [11] "2000-09-07" "2000-08-26" "2000-08-14" "2000-08-03" "2000-07-22"
# [16] "2000-07-11" "2000-06-29" "2000-06-18" "2000-06-06" "2000-05-25"
# [21] "2000-05-14" "2000-05-02" "2000-04-21" "2000-04-09" "2000-03-28"
# [26] "2000-03-17" "2000-03-05" "2000-02-23" "2000-02-11" "2000-01-31"

However when I run it I get the error

Error in seq.int(0, to0 - from, by) : wrong sign in 'by' argument

I can generate the output using the 'length.out' argument instead of 'by'

seq(from = as.Date("2001-01-01"),
    to = as.Date("2000-01-31"),
    length.out = 30)

However I am wondering why the by = "day" argument works for the author but not for me. Has the seq() function changed?

CodePudding user response:

There is a typo in the code i.e. the from is greater than the to

seq(from = as.Date("2001-01-01"), to = as.Date("2000-01-31"), by = "day")
                       ^

It should be either

seq(from = as.Date("2000-01-01"), to = as.Date("2000-01-31"), by = "day")

Or specify the by as negative

seq(from = as.Date("2001-01-01"), to = as.Date("2000-01-31"), by = "-1 day")

There is a stop check in the seq.default source code

...
  if (n < 0L) 
                stop("wrong sign in 'by' argument")
...
  •  Tags:  
  • r
  • Related