Time series, lubridate, and the seq function

I'm just starting my adventure with the lubridate package and the dates in R. And at the beginning I was surprised by some behavior. Because when I do this seq(ymd("2021-01-01"), ymd("2021-01-04"), ddays(1)) I only get one date [1]" 2021-01-01". But when I do this seq(ymd_h("2021-01-01 00"), ymd_h("2021-01-04 00"), ddays(1)) I get the more expected result which is four dates "2021- 01-01 UTC" "2021-01-02 UTC" "2021-01-03 UTC" "2021-01-04 UTC". I admit that it surprised me a lot. I will be very grateful for explaining in simple words why this is happening.

And immediately the second question. Is there any function like seq that would correctly understand the d... functions in the lubridate package (ddays, dhours, dminutes etc)?

1 answer

  • answered 2021-10-22 20:27 Brian Montgomery

    seq is not part of the lubridate package and doesn't understand the d... functions.
    ymd returns a Date, so when you call seq, you are using seq.Date.
    You want seq(ymd("2021-01-01"), ymd("2021-01-04"), "days")

    ymd_h returns a POSIXct object, so then seq is using seq.POSIXct.
    You again want seq(ymd_h("2021-01-01"), ymd_h("2021-01-04"), "days"), but now the result is a POSIXct vector.

    See the help for seq.Date and seq.POSIXct to see how they differ.

    The new clock package has many good functions for date manipulation, including one called date_seq you might find useful.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum