简体   繁体   中英

R: How to extract dates from a time series

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.

Try:

time(myts)

or perhaps:

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

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)

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

The original problem given in the question is uniquely difficult because it contains a non-standard sampling, ie 24 times per year, and therefore you would have to use non-standard ways to extract the dates which others have adequately covered. For those that stumble upon this question that have more standard time series the solution is simpler.

x <- 1:(768/2) ## shorten the ts to reflect lower sampling rate
myts <- ts(x, start = c(1982, 1), frequency = 12) ## now one sample per month
dates <- as.Date(myts)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM