1

我有一个如下所示的数据集:

Date<-c("2009-05-1 10:00:00","2009-05-1 10:05:00","2009-05-1 10:10:00",
"2009-05-1 10:15:00","2009-05-1 10:20:00","2009-05-1 10:25:00")

Dates<-strptime(Date, "%Y-%m-%d %H:%M:%S")

DF<-data.frame(Dates,X=1:6, Y=1:6)

DF
                Dates X Y
1 2009-05-01 10:00:00 1 1
2 2009-05-01 10:05:00 2 2
3 2009-05-01 10:10:00 3 3
4 2009-05-01 10:15:00 4 4
5 2009-05-01 10:20:00 5 5
6 2009-05-01 10:25:00 6 6

照原样,时间戳是每 5 分钟一次。但是我需要每分钟都有一个数据集,所以我希望首先添加丢失的分钟数据,然后估计XY列数据。该X列是上面数据的简单填充,并且Y是上面/下面数据的平均值。

结果希望如下所示:

              Dates X  Y
2009-05-01 10:00:00 1  1
2009-05-01 10:01:00 1  1.5
2009-05-01 10:02:00 1  1.5
2009-05-01 10:03:00 1  1.5
2009-05-01 10:04:00 1  1.5
2009-05-01 10:05:00 2  2
2009-05-01 10:06:00 2  2.5
2009-05-01 10:07:00 2  2.5
2009-05-01 10:08:00 2  2.5
2009-05-01 10:09:00 2  2.5
2009-05-01 10:10:00 3 3
2009-05-01 10:11:00 3 3.5
2009-05-01 10:12:00 3 3.5
2009-05-01 10:13:00 3 3.5
2009-05-01 10:14:00 3 3.5
2009-05-01 10:15:00 4 4
2009-05-01 10:16:00 4 4.5
2009-05-01 10:17:00 4 4.5
2009-05-01 10:18:00 4 4.5
2009-05-01 10:19:00 4 4.5
2009-05-01 10:20:00 5 5
2009-05-01 10:21:00 5 5.5
2009-05-01 10:22:00 5 5.5
2009-05-01 10:23:00 5 5.5
2009-05-01 10:24:00 5 5.5
2009-05-01 10:25:00 6 6

任何关于如何进行此操作的想法将不胜感激。

4

1 回答 1

4

这是一种方法:

Date <- c("2009-05-1 10:00:00","2009-05-1 10:05:00","2009-05-1 10:10:00","2009-05-1 10:15:00","2009-05-1 10:20:00","2009-05-1 10:25:00")

Dates <- strptime(Date, "%Y-%m-%d %H:%M:%S")

DF <- data.frame(Dates,X=1:6, Y=1:6)
DF2 <- merge(DF,data.frame(Dates=DF$Dates - 5 * 60, YNext=DF$Y),by='Dates',all.x=T,all.y=F)
DF3 <- merge(DF2,data.frame(Dates=seq(from=min(DF2$Dates),to=max(DF2$Dates),by='1 min')),by='Dates',all=TRUE)

tmpFun <- function(d){
  d$X <- na.omit(d$X)[1]
  d$Y <- ifelse(is.na(d$Y),(na.omit(d$Y)[1] + na.omit(d$YNext)[1]) / 2,d$Y)
  return(d)
}

DF4 <- do.call(rbind,by(DF3,INDICES=(as.POSIXlt(DF3$Dates)$min %/% 5),FUN=tmpFun))

# "beautify" the data.frame (set the row names, and remove the YNext column)
row.names(DF4) <- 1:nrow(DF4)
DF4$YNext <- NULL

结果:

> DF4
                 Dates X   Y
1  2009-05-01 10:00:00 1 1.0
2  2009-05-01 10:01:00 1 1.5
3  2009-05-01 10:02:00 1 1.5
4  2009-05-01 10:03:00 1 1.5
5  2009-05-01 10:04:00 1 1.5
6  2009-05-01 10:05:00 2 2.0
7  2009-05-01 10:06:00 2 2.5
8  2009-05-01 10:07:00 2 2.5
9  2009-05-01 10:08:00 2 2.5
10 2009-05-01 10:09:00 2 2.5
11 2009-05-01 10:10:00 3 3.0
12 2009-05-01 10:11:00 3 3.5
13 2009-05-01 10:12:00 3 3.5
14 2009-05-01 10:13:00 3 3.5
15 2009-05-01 10:14:00 3 3.5
16 2009-05-01 10:15:00 4 4.0
17 2009-05-01 10:16:00 4 4.5
18 2009-05-01 10:17:00 4 4.5
19 2009-05-01 10:18:00 4 4.5
20 2009-05-01 10:19:00 4 4.5
21 2009-05-01 10:20:00 5 5.0
22 2009-05-01 10:21:00 5 5.5
23 2009-05-01 10:22:00 5 5.5
24 2009-05-01 10:23:00 5 5.5
25 2009-05-01 10:24:00 5 5.5
26 2009-05-01 10:25:00 6 6.0
于 2012-09-20T08:34:01.990 回答