maximusdooku - 1 month ago 7

R Question

I have large number of dates in this format:

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

And I have to add/subtract numbers that may not always be whole numbers.I am using 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?

Answer

The error is occurring with `days(1.5)`

, which doesn't allow fractional periods. You could do:

```
dt - days(1) - hours(12)
```

or

```
dt - 1.5*24*3600
```

or there's probably a base date function that guys like @DirkEddelbuettel know about that would work also. Ah, it's `difftime`

(I don't work with dates enough to remember these things off the top of my head).

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

And, as pointed out by @maximusdooku:

```
dt - ddays(1.5)
```

(Based on the code, it looks like `ddays`

just returns the number of seconds in the requested time period, plus some class information.)

Source (Stackoverflow)

Comments