I have a vector of dates and a vector of number-of-days.
dates <- seq(Sys.Date(), Sys.Date()+10, by='day')
number.of.days <- 1:4
I need to get a list with an entry for each number-of-days, where each entry in the list is the dates vector minus the corresponding number-of-days, ie.,
list(dates-1, dates-2, dates-3, dates-4)
The defintion of -
(function (e1, e2) .Primitive("-")
) indicates that its first and second arguments are e1
and e2
, respectively. So the following should work.
lapply(number.of.days, `-`, e1=dates)
But it raises an error.
Error in
-.Date
(X[[i]], ...) : can only subtract from "Date" objects
Furthermore, the following does work:
lapply(number.of.days, function(e1, e2) e1 - e2, e1=dates)
Is this a feature or a bug?
You can use:
Part of the problem is
-
is a primitive which doesn't do argument matching. Notice how these are the same:From R Language Definition:
So in your case, you end up using
dates
as the second argument to-
even though you attempt to specify it as the first. By using the "Date" method for-
, which is not a primitive, we can get it to work.So technically, the behavior you are seeing is a feature, or perhaps a "documented inconsistency". The part that could possibly considered a bug is that R will do a multiple dispatch to a "Date" method for
-
despite that method not supporting non-date arguments as the first argument: