I would like to calculate the number of days to the next meeting given this as sample.
meetings=c("2023-06-21","2023-05-03","2023-03-22","2023-02-01","2022-12-07")
dates=c("2023-08-01","2023-04-01","2023-03-01","2023-02-01","2023-01-01")
and returning this
c(NA,32,21,0,31)
I have tried this but does not consider all meetings
as.Date(meetings)-as.Date(dates)
Time differences in days
[1] -41 32 21 0 -25
First transform to date with as.Date
. Sort the dates then use sapply
, after defining next_meeting use difftime
:
meetings <- as.Date(c("2023-06-21", "2023-05-03", "2023-03-22", "2023-02-01", "2022-12-07"))
dates <- as.Date(c("2023-08-01", "2023-04-01", "2023-03-01", "2023-02-01", "2023-01-01"))
meetings <- sort(meetings)
sapply(dates, function(date) {
next_meeting <- meetings[which(meetings >= date)][1]
if (is.na(next_meeting)) {
return(NA)
} else {
return(as.integer(difftime(next_meeting, date, units = "days")))
}
})
output:
[1] NA 32 21 0 31