35

How can I extract dates from a times series? Here is a time series:

x = seq (1, 768)
myts <- ts(x, start=1982, frequency=24)

Originally I needed to create a vector holding date/time data for the rts function, The observations start 1982 with 2 measurements per month going till 2013.

Liza
  • 1,066
  • 2
  • 16
  • 26

3 Answers3

56

Try:

time(myts)

or perhaps:

library(zoo)
as.yearmon(time(myts))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • if frequency = 12 then can use zoo::as.Date. x = seq (1, 768); myts <- ts(x, start=1982, frequency=12); zoo::as.Date(myts) – Renhuai Jan 22 '21 at 16:10
12

In case you need POSIX* objects -- which is probably not appropriate when working with half-monthly data, but might come in handy when dealing with higher temporal resolutions -- you could also use date_decimal from lubridate.

library(lubridate)
mts <- as.numeric(time(myts))

## 'POSIXct, POSIXt' object
tms <- date_decimal(mts)
fdetsch
  • 5,239
  • 3
  • 30
  • 58
2

You can use the following function. The input is a time series in r. And the output is a list containing all time array from the start time to the end time.

With the help of the list, you can use window() function to truncate a time series very conveniently.

getTStime <- function(ats){
  start <- start(ats)
  end <- end(ats)
  time <- list()
  time[[1]] <- start
  m <- 2
  while(!(identical(start, end))){
    start[2] <- start[2] + 1
    if (start[2]==13){
      start[1] <- start[1] + 1
      start[2] <- 1
    }
    time[[m]] <- start
    m <- m + 1
  }
  return(time)
}
Jason Lian
  • 21
  • 1