【问题标题】:Creating a specific sequence of date/times in R在 R 中创建特定的日期/时间序列
【发布时间】:2012-12-10 03:57:23
【问题描述】:

我想创建一个单列,其日期/时间序列每小时增加一年或一个月(例如)。我正在使用这样的代码来生成这个序列:

start.date<-"2012-01-15"
start.time<-"00:00:00"
interval<-60 # 60 minutes
increment.mins<-interval*60 
x<-paste(start.date,start.time)

for(i in 1:365){
   print(strptime(x, "%Y-%m-%d %H:%M:%S")+i*increment.mins)
}

但是,我不确定如何指定日期和时间序列的范围。另外,我在处理第一个小时“00:00:00”时遇到了问题?不确定指定月份、年份等日期/时间序列长度的最佳方法是什么?任何建议将不胜感激。

【问题讨论】:

    标签: r datetime sequence


    【解决方案1】:

    我强烈建议您使用POSIXct 数据类型。这样您就可以毫无问题地使用seq 并根据需要使用这些数据。

    start <- as.POSIXct("2012-01-15")
    interval <- 60
    
    end <- start + as.difftime(1, units="days")
    
    seq(from=start, by=interval*60, to=end)
    

    现在您可以对时间戳向量做任何您想做的事情。

    【讨论】:

      【解决方案2】:

      试试这个。 mondate 非常聪明,提前一个月。例如,它将 1 月的最后一天提前到 2 月的最后一天,而其他日期/时间类往往会超过 3 月。chron 不使用时区,因此您无法获得与您一样编码的时区错误可以使用 POSIXct。这里x来自问题。

      library(chron)
      library(mondate)
      
      start.time.num <- as.numeric(as.chron(x))
      
      # +1 means one month.  Use +12 if you want one year.
      end.time.num <- as.numeric(as.chron(paste(mondate(x)+1, start.time)))
      
      # 1/24 means one hour.  Change as needed.
      hours <- as.chron(seq(start.time.num, end.time.num, 1/24))
      

      【讨论】:

        猜你喜欢
        • 2018-09-30
        • 2015-08-19
        • 2016-03-29
        • 2021-11-07
        • 1970-01-01
        • 2022-11-23
        • 2022-10-16
        • 2020-04-28
        • 2018-10-03
        相关资源
        最近更新 更多