Is there an efficient way to generate a time-sequence vector with tidyverse
and lubridate
? I know the two can work with seq()
when one use the number of dates as the interval. For example, with the input:
seq(today(), today()+dyears(1), 60)
one can get a series of dates with a 60-day interval
"2017-02-14" "2017-04-15" "2017-06-14" "2017-08-13" "2017-10-12" "2017-12-11" "2018-02-09"
However, is there any way that this can work for weeks, months and years as well? Perhaps something similar to the code below, which I thought would work but did not:
seq(as_date(2000-01-01), as_date(2017-01-01), dyears(1))
Error: Incompatible duration classes (Duration, numeric). Please coerce with
as.duration
.
I know it is possible to change dyears(1)
into 365
or 30
if one only need an approximation for year or month, but was wondering whether there are smarter ways to take leap years and months into account.
To provide more context, I would like to generate a date vector so I can customize the scale_x_date
in ggplot
. Instead of letting the waiver()
display 2000, 2003, 2006, 2009, I want the plot to have all individual years or even every three-month period if possible.
you could try using seq.Date():
seq.Date(from=as.Date("2000-01-01"), to=as.Date("2010-01-01"), by="month")
or:
seq(as.Date("2000/1/1"), by = "month", length.out = 12)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With