How to Extract Time Interval Information from a tsibble Object in R?

66 views Asked by At

I have a tsibble object in R and I would like to extract the time interval information (e.g., "7W") from it. Here's a simplified example:

library(tsibble)

df_weekly <- tsibble(tibble(
  customer = c("X", "X"),
  week = yearweek(c("2022-08-20", "2022-10-08")),
  value = c(1, 0),
), index=week, key=customer
)

print(df_weekly)

The output looks like this:

# A tsibble: 2 x 3 [7W]
# Key:       customer [1]
  customer     week value
  <chr>      <week> <dbl>
1 X        2022 W33     1
2 X        2022 W40     0

Now, I want to programmatically extract the time interval information (e.g., "7W") from this tsibble object. How can I do this in R? Is there a function or method available for this purpose?

I'd appreciate any help or suggestions on how to achieve this.

2

There are 2 answers

2
Ronak Shah On

tsibble::interval provides you with that information.

tsibble::interval(df_weekly)

#<interval[1]>
#[1] 7W
0
aeongrail On

You will want to convert the interval into a duration, from there you can convert it to base numeric types.

library(lubridate)
library(tsibble)

x <- new_interval(hour = 1, minute = 30)
x
#> <interval[1]>
#> [1] 1h 30m
x %>% lubridate::as.duration() %>% as.numeric()
#> [1] 5400

So in your example:

df_weekly %>% interval() %>% as.duration() %>% as.character()
#> [1] "4233600s (~7 weeks)"

You can convert this to a number and/or do comparisons directly