How to convert 10-minute time blocks to 1-minute intervals in R

。_饼干妹妹 提交于 2019-12-11 04:23:35

问题


I wish to convert 10-minute time blocks into 1-minute time blocks for a large vector. My datatime values are spaced at 10-minutes intervals, which represent a 10-minute time block ending at the given time stamp. Example data below:

data<- structure(list(datetime = structure(1:7,  .Label = c("30/11/2011 02:32",
 "30/11/2011 02:42", "30/11/2011 02:52", "30/11/2011 03:02", "30/11/2011 03:12",
 "30/11/2011 03:22", "30/11/2011 03:32"), class = "factor"), count =
c(100L, 60L, 10L, 10L, 200L, 180L, 190L)), .Names = c("datetime", "count"), class =  
"data.frame", row.names = c(NA, -7L))

I have successfully converted the 10-minute time blocks into 1-minute blocks, between the first and last datetime values in my vector, using the xts package as follows:

data$datetime <- strptime(data$datetime, format="%d/%m/%Y %H:%M") 
data$datetime <- as.POSIXct(data$datetime)
data_xts <- as.xts(data, order.by=data$datetime)
dtmins <- seq(start(data_xts$datetime), end(data_xts$datetime), by = "1 min")

However, as the time values relate to the ‘end’ of a 10-minute block, I also require nine rows of 1-minute datetime values to be created, prior to the first datetime row in my vector. I wish to end up with an output vector that looks like the below (and continues on to the last datetime value in my original vector):

datetime
30/11/2011 02:23
30/11/2011 02:24
30/11/2011 02:25
30/11/2011 02:26
30/11/2011 02:27
30/11/2011 02:28
30/11/2011 02:29
30/11/2011 02:30
30/11/2011 02:31
30/11/2011 02:32
30/11/2011 02:33
30/11/2011 02:34
30/11/2011 02:35
30/11/2011 02:36
30/11/2011 02:37
etc...

I am struggling to find a solution. Any help would be much appreciated!


回答1:


Just merge your xts object with the sequence of times you want.

Data <- structure(list(datetime=structure(c(1322641920, 1322642520, 1322643120,
  1322643720, 1322644320, 1322644920, 1322645520), class=c("POSIXct", "POSIXt"),
  tzone=""), count=c(100L, 60L, 10L, 10L, 200L, 180L, 190L)),
 .Names=c("datetime", "count"), row.names=c(NA, -7L), class="data.frame")

data_xts <- as.xts(Data[,-1], order.by=Data$datetime)
data_xts <- merge(data_xts, seq(start(data_xts)-60*9, end(data_xts), by="1 min"))

Then you can use na.locf or similar to fill in the missing values, if you want.

data_xts <- na.locf(data_xts)


来源:https://stackoverflow.com/questions/17407709/how-to-convert-10-minute-time-blocks-to-1-minute-intervals-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!