How to add fractional numbers to R?

I have a large number of dates in this format:

dt = as.POSIXct("2004-04-02 12:45:00 UTC") 

And I need to add / subtract numbers, which may not always be integers. I am using the lubridate library.

Example:

  dt - days(2) [1] "2004-03-31 12:45:00 UTC" 

But,

 dt - days(1.5) Error in validObject(.Object) : invalid class "Period" object: periods must have integer values 

Is there an alternative for this operation?

+5
source share
1 answer

The error occurs with days(1.5) , which does not allow fractional periods. You can do:

 dt - days(1) - hours(12) 

or

 dt - 1.5*24*3600 

or maybe there is a base date function that guys like @DirkEddelbuettel know about. Ah, this is difftime (I do not work with dates to remember these things from my head).

 dt - as.difftime(1.5, units="days") 

And as @maximusdooku pointed out:

 dt - ddays(1.5) 

(Based on the code, it looks like ddays just returns the number of seconds in the requested time period, as well as some class information.)

+7
source

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


All Articles