簡體   English   中英

在 R 中為一天的一部分創建非周末時間間隔的向量

[英]Create vector of non-weekend time intervals for part of a day in R

我有一個原始數據集,僅在工作日的早上 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但我無法弄清楚我在做什么錯或下一步該去哪里。

任何幫助表示贊賞

一個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))))

問題之一是當分鍾超過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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM