简体   繁体   English

R:如何从时间序列中提取日期

[英]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. 最初我需要为rts功能创建一个保存日期/时间数据的向量,观察始于1982年,每月进行2次测量直至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 . 如果您需要POSIX*对象-与半月度数据时,但具有较高的时间分辨率打交道时可能会派上用场这可能是不恰当的-你也可以使用date_decimallubridate。

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. 输入是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. 在列表的帮助下,您可以使用window()函数非常方便地截断时间序列。

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. 问题中给出的原始问题是非常困难的,因为它包含非标准抽样,即每年24次,因此您必须使用非标准方法来提取其他人已充分涵盖的日期。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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