In R, why subtracting numbers from NA returns NA, but subtracting dates from NA returns an error?

In R, if you subtract a number from NA, it will return NA:

> x <- 1
> NA - x
[1] NA

But if you try to subtract the date from NA, it will return an error:

> x <- as.Date("2014-04-22")
> NA - x
Error in `-.Date`(NA, x) : can only subtract from "Date" objects

I am wondering why R returns an error. As I understand it, Date objects are just an expression of the integer difference from the origin (by default - 1970-01-01).

+4
source share
1 answer

This should work:

> as.Date(NA)-as.Date("2014-04-22")
Time difference of NA days

You can, however, subtract an integer from the date:

> as.Date("2014-04-22")-NA
[1] NA
> as.Date("2014-04-22")-2
[1] "2014-04-20"

The reason for this is that the operator -is actually an S3 method - the "overload" (called method selection) is performed according to the type of its first argument. Try:

> get("-.Date")

S4, , .

S3 . .

+5

Source: https://habr.com/ru/post/1537539/


All Articles