【问题标题】:Create vector of non-weekend time intervals for part of a day in R在R中为一天的一部分创建非周末时间间隔的向量
【发布时间】:2015-04-19 17:01:37
【问题描述】:

我有一个原始数据集,仅在工作日早上 6 点到晚上 9 点之间每隔 5 分钟采集一次。这些不附带用于绘图等的日期时间信息,因此我正在尝试创建一个日期时间向量以将其添加到我的数据中。即:

X425 X432 X448 1 0.07994814 0.1513559 0.1293103 2 0.08102852 0.1436480 0.1259074

到这里

X425 X432 X448 2010-05-24 06:00 0.07994814 0.1513559 0.1293103 2010-05-24 06:05 0.08102852 0.1436480 0.1259074

我做了如下处理:

# using lubridate and xts
library(xts)
library(lubridate)

# sequence of 5 min intervals from 06:00 to 21:00
sttime <- hms("06:00:00")
intervals <- sttime + c(0:180) * minutes(5)

# sequence of days from 2010-05-24 to 2010-11-05
dayseq <- timeBasedSeq("2010-05-24/2010-11-05/d")

# add intervals to dayseq
dayPlusTime <- function(days, times) {
  dd <- NULL
  for (i in 1:2) {
    dd <- c(dd,(days[i] + times))}
  return(dd)
}

obstime <- dayPlusTime(dayseq, intervals)`

obstime 将作为列表出现。 days[1] + times 有效,所以我想这与将 POSIXct 对象连接在一起以生成 dd 的方式有关,但我不知道我在做什么错 otr 下一步该去哪里。

任何帮助表示赞赏

【问题讨论】:

    标签: r datetime time-series lubridate


    【解决方案1】:

    base 替代方案:

    # create some dummy dates
    dates <- Sys.Date() + 0:14
    
    # select non-weekend days
    wd <- dates[as.integer(format(dates, format = "%u")) %in% 1:5]
    
    # create times from 06:00 to 21:00 by 5 min interval
    times <- format(seq(from = as.POSIXct("2015-02-18 06:00"),
                        to = as.POSIXct("2015-02-18 21:00"),
                        by = "5 min"),
                    format = "%H:%M")
    
    # create all date-time combinations, paste, convert to as.POSIXct and sort 
    wd_times <- sort(as.POSIXct(do.call(paste, expand.grid(wd, times))))
    

    【讨论】:

      【解决方案2】:

      其中一个问题是,当分钟数超过 60 时,您的区间向量不会改变 hour

      这是您可以做到这一点的一种方法:

      #create the interval vector
      intervals<-c()
      for(p in 6:20){
        for(j in seq(0,55,by=5)){
          intervals<-c(intervals,paste(p,j,sep=":"))
        }      
      }
      intervals<-c(intervals,"21:0")
      
      #get the days
      dayseq <- timeBasedSeq("2010-05-24/2010-11-05/d")
      
      
      #concatenate everything and format to POSIXct at the end
      obstime<-strptime(unlist(lapply(dayseq,function(x){paste(x,intervals)})),format="%Y-%m-%d %H:%M", tz="GMT")
      

      【讨论】:

        猜你喜欢
        • 2014-11-04
        • 1970-01-01
        • 2021-07-14
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 2014-07-28
        • 1970-01-01
        相关资源
        最近更新 更多