如何快速检查大型XTS对象中是否存在日期(或时间)?

Mic*_*elE 1 r zoo rcpp xts

我在R中有一个非常大的xts对象,Data每天有10或100行和数百万行.

这是我目前的代码:

Data #my xts data set.

myDate <- "2018-02-15"
if(nrow(Data[as.character(myDate)]) > 0)
   #Run code.
Run Code Online (Sandbox Code Playgroud)

问题是1天的子集有数百万行并且需要花费大量时间,特别是如果我检查许多日期.

有没有办法可以检查日期是否存在,或者只是第一次出现日期,这样我就不会浪费时间提取大量数据?

我想在原生R中做到这一点,但Rcpp解决方案是最受欢迎的.

谢谢.

编辑:从ngm的回答我能够完成一个Rcpp解决方案.

// [[Rcpp::export]]
bool doesDateExist(const Rcpp::NumericMatrix& Data, double startDate, double maxDiff = 86400)
{
  double endDate = startDate + maxDiff;
  NumericVector time = Data.attr("index");
  for(int ii = 0; ii < Data.nrow();ii++)
  {
     if(time(ii) >= startDate)
     {
       if(time(ii) < endDate)
          return true;
       else
         return false;
     }
  }
  return false;
}
Run Code Online (Sandbox Code Playgroud)

要使用它,我有:

myDate <-as.POSIXct("2018-02-15", tz = indexTZ(Data))
if(doesDateExist(Data, myDate, 86400))
   #Run code.
Run Code Online (Sandbox Code Playgroud)

as.POSIXct是我一直忘记的遗失的部分.

编辑:为rcpp代码添加了ptional字段以获得最大时差.白天为86400秒,小时为6000分钟,依此类推.

Dir*_*tel 5

以下是使用的反例%in%:

R> x <- xts(1:20, 
+           order.by=Sys.time() + cumsum(sample(1:10, 20, TRUE)*1e-6))
R> x
                           [,1]
2018-04-05 12:09:12.818800    1
2018-04-05 12:09:12.818805    2
2018-04-05 12:09:12.818809    3
2018-04-05 12:09:12.818810    4
2018-04-05 12:09:12.818819    5
2018-04-05 12:09:12.818827    6
2018-04-05 12:09:12.818832    7
2018-04-05 12:09:12.818837    8
2018-04-05 12:09:12.818843    9
2018-04-05 12:09:12.818847   10
2018-04-05 12:09:12.818848   11
2018-04-05 12:09:12.818849   12
2018-04-05 12:09:12.818858   13
2018-04-05 12:09:12.818867   14
2018-04-05 12:09:12.818872   15
2018-04-05 12:09:12.818877   16
2018-04-05 12:09:12.818881   17
2018-04-05 12:09:12.818888   18
2018-04-05 12:09:12.818889   19
2018-04-05 12:09:12.818890   20
R> reftime <- anytime::anytime("2018-04-05 12:09:12.818832")
R> reftime
[1] "2018-04-05 12:09:12.818831 CDT"
R> reftime %in% index(x)
[1] FALSE
R> 
Run Code Online (Sandbox Code Playgroud)

我实际上复制并粘贴了一个随机条目(值为7)并重新解析它.然而%in%失败了.

R FAQ 7.31之后可以做类似的事情

R> which( abs(reftime - index(x)) < 1e-6)
[1] 7
R> 
R> x[which( abs(reftime - index(x)) < 1e-6)]
                           [,1]
2018-04-05 12:09:12.818832    7
R> 
Run Code Online (Sandbox Code Playgroud)