在时间间隔内插入NA

时间:2018-06-23 16:44:14

标签: r plot time-series na

我有一个要绘制的时间序列数据集,但是时间序列的数据缺口很大。在绘制此数据集时,R用一条直线在这些间隙上绘制图形,我希望最终图形不要在这些数据间隙上绘制图形。我知道如何解决此问题的唯一方法是在数据集中的间隙之间手动插入一行NA。为此,我编写了一个遍历数据框的函数。该功能有效,但运行速度非常慢。

-m

在R中有更有效的方法吗?

示例数据:

#Define Function to Insert NA in long stretches so don't plot line 

PlotSpace<-function(DF){

NROW<-nrow(DF)
for(t in seq(1:NROW)){

TimeDiff<-difftime(DF$TimeStamp[t+1], DF$TimeStamp[t], units = "hours") 
DF[t,"TimeDiff"]<-TimeDiff  

if( !is.na(TimeDiff) & TimeDiff > 5 ){

    NewTimeStamp<-DF$TimeStamp[t] + 1
    NewProfStamp<-DF$ProfStamp[t] + 1
    print(NewTimeStamp)
    DF<-rbind(DF,NA) #Add last row that is NA
    DF[nrow(DF),'TimeStamp']<-NewTimeStamp
    DF[nrow(DF),'ProfStamp']<-NewProfStamp




    }
}

DF <- DF[order(DF$TimeStamp),]
DF<-DF[-1,]
DF$TimeStamp<-as.POSIXct(DF$TimeStamp)

return(DF)

}

如您所见,上图绘制了7小时数据间隔之间的一条线。我想在差异大于2小时的任何时间之间插入一个NA。又名

 TimeStamp<-c("2015-05-01 10:00:00","2015-05-01 10:05:00","2015-05-01 10:10:00","2015-05-01 10:15:00",
"2015-05-01 10:20:00","2015-05-01 15:00:00","2015-05-01 15:05:00","2015-05-01 15:10:00"
,"2015-05-01 15:20:00","2015-05-01 15:30:00","2015-05-01 15:35:00")

Data<-c(1,2,3,4,5,3,7,8,9,2,11)

DF<-data.frame(TimeStamp, Data)

DF$TimeStamp<-as.POSIXct(DF$TimeStamp)

plot(DF$TimeStamp, DF$Data, type='l')

1 个答案:

答案 0 :(得分:1)

library(data.table)
setDT(DF)

# Create indicator for time gap
DF[, gap := c(diff(TimeStamp) > 2*60, F)]
# If there's a gap, add a new row
DF[, if(gap) rbind(.SD, .(TimeStamp = TimeStamp + 60), fill = T)
     else .SD
   , by = 1:nrow(DF)
   ][, -'gap']
#               TimeStamp Data
#  1: 2015-05-01 10:00:00    1
#  2: 2015-05-01 10:05:00    2
#  3: 2015-05-01 10:10:00    3
#  4: 2015-05-01 10:15:00    4
#  5: 2015-05-01 10:20:00    5
#  6: 2015-05-01 10:21:00   NA
#  7: 2015-05-01 15:00:00    3
#  8: 2015-05-01 15:05:00    7
#  9: 2015-05-01 15:10:00    8
# 10: 2015-05-01 15:20:00    9
# 11: 2015-05-01 15:30:00    2
# 12: 2015-05-01 15:35:00   11