R's trunc and round not working for class Date?

Viewed 464

Judging from the documentation, I feel like I should be able to use round and trunc for "Date" objects. However, it seems to be working only when I first convert it to "POSIXct".

> d <- as.Date('2019-10-21')
> trunc(d,'months')
[1] "2019-10-21"
> trunc(as.POSIXct(d),'months')
[1] "2019-10-01 CEST"
> round(as.POSIXct(d),'months')
[1] "2019-11-01 CET"
> round(d,'months')
Error in round.default(18190, "months") : 
  non-numeric argument to mathematical function

I expected the same output for both the date and posix classes. Am I misunderstanding something here?

2 Answers

Upon re-reading the documentation it is clear to me that the documented behaviour is different for the "Date" and "POSIXt" class. The units arguments is omitted in the usage example for "Date". I just misinterpreted the documentation the first time I read it. You have to first convert to POSIX to be able to round and trunc with respect to a unit.

?trunc.Date

S3 method for class 'POSIXt'

trunc(x, units = c("secs", "mins", "hours", "days", "months", "years"), ...)

S3 method for class 'Date'

trunc(x, ...)

and also:

The methods for class "Date" are of little use except to remove fractional days.

?trunc

trunc takes a single numeric argument x and returns a numeric vector containing the integers formed by truncating the values in x toward 0.

round rounds the values in its first argument to the specified number of decimal places (default 0).

d <- as.Date('2019-10-21')
class(d)
#[1] "Date"

Regarding the POSIXct class, probably it has got to do with them being a number of seconds since origin.

I usually use r-base functions or not in the purpose they are intended unless it has to do with testing the unintended.

Related