as_tsibble.ts how to get correct timestamps when importing ts with daily value

Hi,

I have a simple ts object which contains daily values (frequency = 365). When I import it into tsibble via as_tsibble I do not get exactly daily data. I get timestamps that are closed to daily but have a small offset.
Here is a simple reprex showing the issue: as you can see the timestamps have slight 9 seconds offset.
Any workaround for this?

library(tsibble); as_tsibble(ts(1:3, frequency = 365, start = 2010))
#> # A tsibble: 3 x 2 [1s]
#> index value
#>
#> 1 2010-01-01 00:00:00 1
#> 2 2010-01-02 00:00:09 2
#> 3 2010-01-02 23:59:46 3

Thank you,
Emmanuel

Hi,

You can round the dates up or down like this:

myData = as_tsibble(ts(1:3, frequency = 365, start = 2010))
myData$index = as.Date(round.POSIXt(myData$index, units = "days"))

> [1] "2010-01-01 UTC" "2010-01-02 UTC" "2010-01-03 UTC"

Grtz,
PJ

I get the message "Error: Unsupported index type: POSIXlt" if I type myData in the Console.

Rounding and then converting from dttm to date format works for me.

library(dplyr)
library(lubridate)

myData <-  as_tsibble(ts(1:3, frequency = 365, start = 2010)) %>% 
  mutate(index = as_date(round_date(index, unit = "day")))

This is my first post, so please excuse any errors.

1 Like

Hi,

You're right, I corrected it :slight_smile: Thanks for testing!

PJ

PJ,

The output is now a tsibble but its interval is stuck at [1s] not [1D]:

A tsibble: 3 x 2 [1s]
index value
date dbl
1 2010-01-01 1
2 2010-01-02 2
3 2010-01-03 3

Using lubridate and tsibble's mutate() instead of base R, I get:

A tsibble: 3 x 2 [1D]
index value
date dbl
1 2010-01-01 1
2 2010-01-02 2
3 2010-01-03 3

John

Hi John,

Could you explain what the difference is between [1s] and [1D], I'm unfamiliar with tibbles (still stuck with data frames I'm afraid :slight_smile:)

PJ

PJ,

A tsibble is a time-aware tibble. It uses a date column as a time index (and if needed, one or more key columns). For regularly-spaced data it stores the interval between observations, which appears in the [
] when printed to Console. The tsibble package uses that interval for many of its functions. [1M] is for monthly and [1m] is for minutes. For irregular-spaced data, it is [!]. I think that to change the time interval from seconds to days you need to use tsibble's mutate() on the index column rather than myData$index = . Then again, I am trying to quickly learn tsibble and the other new tidyverts forecasting packages for a fall class, so am definitely not an authority.

John

1 Like

Got it thank you very much!

This solution:

as_tsibble(ts(1:3, frequency = 365, start = 2010)) %>% 
  mutate(index = as_date(round_date(index, unit = "day")))

Worked great for me

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.