Trying to build a vector of dates

dplyr
lubridate

#1

I'm trying to build a long vector of dates: I have the final date (today) and I know the duration (n*m minutes). However, to create a seq, I need a start_date, and the %--% is complaining that I need an origin. Can you help me solve this?

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date

# define data set
m <- 3
n <- 10^4
stop_date <- now()
period <- minutes(n*m) 
start_date <- stop_date %--% period
#> Error in as.POSIXct.numeric(x, tz = tz): 'origin' must be supplied
date_time <- seq(start_date, stop_date, length.out = n*m)
#> Error in seq(start_date, stop_date, length.out = n * m): oggetto "start_date" non trovato

Created on 2018-09-10 by the reprex
package
(v0.2.0).


Struggling to create a scatter plot with time span
#2

Interval from lubridate takes 2 datetime objects and you are supplying only one. Second object is just a number. You can do what you want if you simply create start_date by subtracting period from stop_date:

library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date
m <- 3
n <- 10^4
stop_date <- now()
period <- minutes(n*m) 
start_date <- stop_date - period
intv <- start_date %--% stop_date
date_time <- seq(start_date, stop_date, length.out = n*m)
length(date_time)
#> [1] 30000

Created on 2018-09-10 by the reprex package (v0.2.0).


#3

@mishabalyasin I misunderstood the API - I thought %--% was a difference operator, not an interval operator. Is there a difference operator? I.e., an operator such that subtracting a Period or Duration object from a datetime object, returns another datetime object?


#4

Do you think you need a special operator for that? Why wouldn't - work? And how would you subtract period from a datetime object?

In other words, what are you trying to do? :slight_smile:


#5

- is fine. I saw you also introduced the intv variable so I thought it was needed to generate the vector of dates, but it's not: we only need start_date, stop_date and the number of samples, as I thought.


#6

Yes, in fact in this specific case you don't need lubridate at all.
The only reason I've introduced intv is to make sure that %--% is working. As you've said, it's not needed here, so you can skip this step.