我想将下表变成一个以小时为单位递增的两列矩阵。
数据:
START<-as.POSIXct(c("2017-07-13 01:40:00 MDT", "2017-07-21 06:00:00 MDT", "2017-07-21 14:00:00 MDT", "2017-07-24 11:00:00 MDT",
"2017-07-24 12:00:00 MDT", "2017-07-25 05:00:00 MDT", "2017-07-25 17:00:00 MDT", "2017-07-26 12:00:00 MDT",
"2017-07-30 12:00:00 MDT", "2017-07-31 04:00:00 MDT", "2017-07-31 15:00:00 MDT", "2017-08-03 18:30:00 MDT",
"2017-08-03 23:30:00 MDT", "2017-08-09 05:00:00 MDT", "2017-08-09 20:00:00 MDT", "2017-08-14 09:00:00 MDT",
"2017-08-16 05:00:00 MDT", "2017-08-16 07:00:00 MDT", "2017-08-16 19:00:00 MDT", "2017-08-17 18:00:00 MDT",
"2017-08-20 05:00:00 MDT", "2017-08-23 06:00:00 MDT", "2017-08-23 14:00:00 MDT", "2017-08-24 17:00:00 MDT",
"2017-08-28 00:00:00 MDT"))
END<-as.POSIXct(c("2017-07-21 06:00:00 MDT", "2017-07-21 14:00:00 MDT", "2017-07-24 11:00:00 MDT", "2017-07-24 12:00:00 MDT",
"2017-07-25 05:00:00 MDT", "2017-07-25 17:00:00 MDT", "2017-07-26 12:00:00 MDT", "2017-07-30 12:00:00 MDT",
"2017-07-31 04:00:00 MDT", "2017-07-31 15:00:00 MDT", "2017-08-03 18:30:00 MDT", "2017-08-03 23:30:00 MDT",
"2017-08-09 05:00:00 MDT", "2017-08-09 20:00:00 MDT", "2017-08-14 09:00:00 MDT", "2017-08-16 05:00:00 MDT",
"2017-08-16 07:00:00 MDT", "2017-08-16 19:00:00 MDT", "2017-08-17 18:00:00 MDT", "2017-08-20 05:00:00 MDT",
"2017-08-23 06:00:00 MDT", "2017-08-23 14:00:00 MDT", "2017-08-24 17:00:00 MDT", "2017-08-28 00:00:00 MDT",
"2017-09-28 13:00:00 MDT"))
RATE<-c(1485, 0, 1485, 880, 1485, 0, 1485, 1100, 1485, 0, 1485, 1483, 1485, 0, 1485, 1419, 880, 0, 1419, 1485, 1419, 0, 1100, 419, 1100)
DF<-data.frame(START, END, RATE)
结果如下:
日期&lt; -c(&#34; 2017-07-13 01:00:00 MDT&#34;,&#34; 2017-07-13 02:00:00 MDT&#34;,&#34; 2017-07-13 03:00:00 MDT&#34;,......,&#34; 2017-09-28 13:00:00 MDT&#34;)
值&lt; -c(1485,1485,1485,.....,1100)
是否有功能会这样做?
我正在考虑通过以下方式获取日期列表:
tStartDateTime<-trunc(DF$START[1], units = "hours")
tEndDateTime<-trunc(max(DF$END), units = "hours")+60*60
tHours<-difftime( DF,tStartDateTime, units = "hours")
TableHours<-seq(from=tStartDateTime, by="1 hours", length.out=tHours )
但我不确定如何使用之间的值填充结果表。
答案 0 :(得分:1)
这不是最优雅的解决方案,但您可以使用lapply
将数据的每一行扩展为单独的data.frame。这些data.frame中的每一个都包含两列 - 时间:从开始到结束时间的每小时,速率:对应行的复制速率。 do.call(rbind, ...)
将data.frame列表转换为单个data.frame。
library(lubridate)
tmp <- lapply(seq(nrow(DF)), function(x) data.frame(
time = seq(floor_date(DF$START[x], "hour"),
ceiling_date(DF$END[x], "hour"),
"hour"),
rate = DF$RATE[x]))
do.call(rbind, tmp)