Reputation: 10103
I have two vectors of dates A and B. I would like for each date of A, obtain the closest date in B which is greater or superior to the date itself.
(the reason is that B is a list of working days and I need my output to be a working day).
How can I do this in a vectorised manner in R ?
Upvotes: 2
Views: 133
Reputation: 4659
+1 to blindJesse for the apply logic, but care needs to be given to the case where no nearest date exists as well as the the coercion to numeric that occurs:
a <- as.Date(sample(1:20, 5, T), origin=Sys.Date())
#[1] "2012-08-26" "2012-08-31" "2012-08-25" "2012-08-18" "2012-08-20"
b <- as.Date(sample(1:20, 5, T), origin=Sys.Date())
#[1] "2012-08-27" "2012-08-27" "2012-08-25" "2012-08-22" "2012-08-17"
sapply(a, function(x) min(b[b>x]))
#[1] 15579 Inf 15579 15574 15574
# generate the min index instead, catching for no min case
min.indices <- sapply(a, function(x) {
ifelse(length(which.min(b[b>x]))==0, NA, which.min(b[b>x]))
})
b[min.indices]
#[1] "2012-08-27" NA "2012-08-27" "2012-08-22" "2012-08-22"
Upvotes: 2
Reputation: 4613
This should work, though there might be a vectorized solution:
sapply(d1, function(x) min(d2[d2>x]))
Upvotes: 3