且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在R中将10分钟的时间间隔转换为1分钟

更新时间:2023-02-11 23:33:31

只需将您的xts对象与您想要的时间顺序合并。



数据< - 结构(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 data_xts< - merge(data_xts,seq(start(data_xts)-60 * 9,end(data_xts),by =1 min))

然后,您可以使用 na.locf 或类似的内容来填写缺少的值如果你想要的话。

  data_xts<  -  na.locf(data_xts)


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!

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)