30
votes

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.

3

3 Answers

49
votes

Try:

time(myts)

or perhaps:

library(zoo)
as.yearmon(time(myts))
9
votes

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)
2
votes

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)
}